Undoing Things in Git
Probably the most-searched git question there is. Here's the actual decision tree.
Beginner → Advanced
git add), and history (what's committed).
Which command you need depends entirely on which of these three still holds the mistake.
git clean -n first (dry run) — it lists exactly what would be
deleted without deleting it.
git reset moves a branch pointer backward. The three flags control how
much it also touches your index and working tree — this is the single most
misused command in git, so know the table before you run it.
| Flag | Moves branch | Resets index | Resets working tree |
|---|---|---|---|
| --soft | yes | no — changes land back as staged | no |
| --mixed (default) | yes | yes — changes land back as unstaged | no |
| --hard | yes | yes | yes — uncommitted work is gone |
reset rewrites history — it moves what a branch points to, so anyone
who already pulled the old commits now disagrees with you. revert adds a
new commit that undoes an old one's changes, leaving history intact. Once
something is pushed and shared, revert is the safe choice.
git reflog | grep <branch-name>
finds the last known commit hash for a branch you just deleted
git reflog to find HEAD's position right before it started, then
git reset --hard to that hash.