Git Reference / Undoing things
09Undoing things
Pick the tool by what you want to undo and whether it’s been pushed.
| I want to… | Command | Safe after push? |
|---|---|---|
| Discard edits to a file | git restore file.txt | — |
| Unstage a file | git restore --staged file.txt | — |
| Fix the last commit message / add a forgotten file | git commit --amend | No |
| Undo last commit, keep changes staged | git reset --soft HEAD~1 | No |
| Undo last commit, keep changes unstaged | git reset HEAD~1 | No |
| Throw away last commit and its changes | git reset --hard HEAD~1 | No |
| Undo a pushed commit | git revert <sha> | Yes ✓ |
| Revert a merge commit | git revert -m 1 <merge-sha> | Yes ✓ |
| Delete untracked files | git clean -fd (preview: -n) | — |
| Reset branch to match remote | git reset --hard origin/main | — |
| Restore a file from another commit | git restore --source=HEAD~3 file.txt | — |
git reset mode | Moves branch | Staging area | Working dir |
|---|---|---|---|
--soft | ✓ | kept | kept |
--mixed (default) | ✓ | reset | kept |
--hard | ✓ | reset | reset ⚠ |