Git on undoing mistakes
The right undo depends on how far the mistake got
- Not staged: git restore <file> discards your edits to that file. They are gone for good.
- Staged: git restore --staged <file> unstages the file and keeps your edits.
- Committed, not pushed: git commit --amend replaces the last commit with a fixed one.
- Pushed: git revert <commit> adds a new commit that undoes it.
git reset moves your branch back
- git reset HEAD~1 moves the branch back one commit. The mode decides what else changes.
- --hard also throws away your uncommitted changes. Treat those as lost.
- Use reset only on commits you have not pushed.
| Mode | Staging area | Working tree |
|---|---|---|
| --soft | Unchanged: the undone work stays staged | Unchanged |
| --mixed (default) | Reset: nothing is staged | Unchanged: your edits are kept |
| --hard | Reset: nothing is staged | Overwritten: your edits are lost |
git revert undoes a commit without rewriting history
- It adds a new commit that makes the opposite change. The old commit stays in history.
- Nothing is replaced, so it is safe on main and other shared branches.
- To revert a merge commit, add -m 1 to name the parent whose side you keep.
The reflog is your safety net
- git reflog lists every commit HEAD has pointed to, newest first.
- Undo a bad reset, rebase or amend by resetting to the entry from before it.
- Bring back a deleted branch with git branch <name> <commit>.
- It is local to your machine. Entries expire after 90 days by default.
$ git reflog
c7d261f HEAD@{0}: reset: moving to HEAD~1
f6b1000 HEAD@{1}: commit: Add three
$ git reset --hard HEAD@{1}
HEAD is now at f6b1000 Add threeStash parks unfinished work
- git stash saves your uncommitted changes and leaves a clean working tree.
- git stash pop puts them back on whatever branch you are on now.
- New files Git is not tracking yet stay behind unless you use git stash -u.
Bisect finds the commit that broke it
- Run git bisect start, then git bisect bad, then git bisect good <older commit>.
- Git checks out a commit halfway between. Test it and mark it good or bad.
- Each answer halves the range, so 1,000 commits take about 10 steps.
- git bisect run <command> does the testing for you. git bisect reset ends it.