Undoing Changes: Reset, Revert, Restore, Reflog and Stash
Know exactly which of the three trees (HEAD, index, working tree) each undo command touches, which undos are safe on shared history, and how to get back from mistakes with the reflog.
Key points
- 1
git restore <path>rewrites the working tree from the index;git restore --staged <path>rewrites the index from HEAD.--source=<commit>picks another source. - 2
git resetmoves the branch:--softstops there,--mixed(default) also resets the index,--hardalso resets the working tree.--keepand--mergeare safer hard resets. - 3
Path-limited
git reset <commit> -- <path>only rewrites the index entry;--softand--hardreject paths. - 4
git revertadds an inverse commit, so it is the safe undo for published history. Merges need-m 1, and re-landing a reverted merge means reverting the revert first. - 5
The reflog (
HEAD@{n},ORIG_HEAD) recovers commits after a bad reset or deleted branch. It is local only, and by default expires after 90 days (reachable) and 30 days (unreachable). - 6
git stashsaves tracked changes;-uadds untracked files and-aignored ones. A conflicting pop keeps the entry, andpop --indexrestores what was staged. - 7
git cleanremoves untracked files only with-f; add-dfor directories,-xto include ignored files, or-Xfor ignored files only. Preview with-n.
Common traps
git reset --hardleaves untracked files but deletes files that were staged and never committed. Unstaged edits it discards cannot be recovered.Reverting a merge undoes its content, not its history: merging the same branch again brings nothing back until you revert the revert.
Plain
git stash popbrings staged changes back unstaged, and a dropped stash is only recoverable as a dangling commit until gc prunes it.
Test yourself on Undoing Changes: Reset, Revert, Restore, Reflog and Stash
Ten questions, with the answer and explanation after each one.