Undoing Things in Git: restore, reset, revert and reflog
Git rarely loses work for good. Pick the right command for what you want to undo and where the change currently lives.
Discard uncommitted changes
git restore src/cart.js # throw away edits to a file (careful: not recoverable)
git restore --staged src/cart.js # unstage, keep the edits
git stash # set changes aside; bring back with git stash pop
Fix the last commit
git commit --amend -m "Better message"
git add forgotten-file.js && git commit --amend --no-edit
Only amend commits you haven't pushed (or that only you use).
Undo local commits with reset
git reset --soft HEAD~1 # undo the commit, keep changes staged
git reset HEAD~1 # undo the commit, keep changes unstaged (default --mixed)
git reset --hard HEAD~1 # undo the commit AND discard its changes
Undo pushed commits with revert
git revert 3f2a1c4 # creates a new commit that reverses 3f2a1c4
git revert -m 1 9d8c7b6 # revert a merge commit (keep parent 1's side)
revert doesn't rewrite history, so it's the safe choice for anything already shared.
Recover "lost" work with reflog
The reflog records every position HEAD has been at, including commits you reset away or branches you deleted:
git reflog
# a1b2c3d HEAD@{0}: reset: moving to HEAD~3
# 9f8e7d6 HEAD@{1}: commit: Add payment retries <- the work you lost
git branch rescue 9f8e7d6 # get it back on a branch
Quick reference
- Edited a file by mistake:
git restore <file>. - Staged the wrong file:
git restore --staged <file>. - Bad last commit, not pushed:
git commit --amendorgit reset --soft HEAD~1. - Bad commit already pushed:
git revert <sha>. - "I've lost everything":
git reflog.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.