Mistakes are fixable.
Git is a safety net. Learn which undo to use, from gentle to dangerous, and how to tell them apart.
Pick the undo that fits
least scary firstEdited, not staged
git restore f puts the committed version back.
Staged by mistake
git restore --staged f unstages it. The file is untouched.
Typo in the last message
git commit --amend -m "new message" replaces the last commit. Only do this before you share it.
Wrong last commit
git reset --soft HEAD~1 keeps your work staged. --hard discards it.
Already shared
git revert HEAD --no-edit adds a new commit that cancels the old one. History is never rewritten.
Lost a commit
git reflog lists where HEAD has been. Copy the spot you want and git reset --hard HEAD@{1} goes back.
What does each undo lose?
read before you typegit restore fgit restore --staged fgit commit --amendgit reset --soft HEAD~1git reset HEAD~1git reset --hard HEAD~1git revert HEADRule of thumb: work that was committed is hard to lose. Work that was never committed is not. The reflog is a safety net, not a vault: it forgets old entries after a while. Other commands can also discard work, for example git clean and deleting files, so slow down when a command says "force" or "hard".
When it goes wrong
real messages, plain meaningfatal: ambiguous argument 'HEAD~5': unknown revision or path not in the working tree.You went further back than your historyRun git log --oneline to count your commits first.error: your local changes would be overwritten by revert.Uncommitted work is in the wayCommit it or restore it, then try again.Author identity unknownGit needs your name and email to record amend and revertSee Chapter 5.Time machine: the reflog
interactiveThe reflog remembers every place HEAD has been, even commits you reset away. Slide back to find them.
History at this moment
todo.txt at this moment
Go back here
Practice: undo a commit
hands-onAmend a message, try the gentle undo, then the dangerous one, then get it back with the reflog and finish with a revert.