Undoing mistakes
restore, reset and revert — and how git reflog rescues commits you thought were gone forever.
Pick the right tool
| Situation | Command |
|---|---|
| Discard uncommitted edits to a file | git restore file |
| Unstage a file (keep edits) | git restore --staged file |
| Undo last commit, keep changes | git reset --soft HEAD~1 |
| Undo last commit, discard changes | git reset --hard HEAD~1 |
| Undo a pushed commit safely | git revert <sha> |
| Remove untracked files | git clean -fd |
⚠️
reset --hard permanently discards working-tree changes. Anything uncommitted there is unrecoverable — check git status first.Revert keeps history honest
revert does not erase anything: it adds a new commit that applies the inverse change. That is exactly why it is the correct way to undo work that is already public.
git revert <sha> # single commit
git revert <old>..<new> # range (not including old)
git revert -m 1 <merge> # specify parent for a merge commitreflog: the safety net
Git records every position HEAD has held. For a while after a mistake — a bad reset, a deleted branch — your commits still exist and can be recovered.
git reflog
git reset --hard HEAD@{3} # return to that state
git checkout -b recovered <sha> # rescue onto a new branch💡
Reflog is local and expires (90 days for reachable entries by default). It is a recovery tool, never a backup strategy — push important work.
FAQ
I staged a secret by accident. Now what?
Unstage with
git restore --staged, remove it from the file, and rotate the credential if it was ever pushed — history retains it otherwise.reset or checkout for a file?
Use
git restore <file> to discard edits and git restore --source=<sha> <file> to take a file from another commit.Related
Conflicts, stash and cherry-pick Git basics
Last refreshed 2026-09-17.