Undoing mistakes safely
Restore files, amend commits, revert and stash.
Almost everything in Git can be undone, if you pick the right tool. The key question: has the commit been shared?
| Situation | Command |
|---|---|
| Discard edits to a file you have not staged | git restore file.txt |
| Unstage a file but keep the edits | git restore --staged file.txt |
| Fix the last commit message or add a forgotten file | git commit --amend |
| Undo a commit that is already shared | git revert <commit> |
| Park unfinished work for later | git stash then git stash pop |
| See where HEAD has been, to recover lost commits | git reflog |
revert vs reset
git revert adds a new commit that cancels an old one: history stays intact, so it is safe on shared branches. git reset --hard moves the branch back and discards work: use it only on local, unshared commits.
Carefulgit reset --hard and git restore on unsaved edits permanently delete changes that were never committed.
Inspecting before acting
git diff # unstaged changes
git diff --staged # staged changes
git show <commit> # one commit in detail
git log --oneline --graph # the shape of the historyTest yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.