Everyone makes Git mistakes. The good news: Git almost never truly deletes anything. This cheatsheet covers every common "oh no" scenario and how to recover from it.
Undo Scenarios
Undo the Last Commit (Keep Changes)
Soft reset — uncommit but keep your edits stagedbash
1
git reset --soft HEAD~1
Your changes are back in the staging area, ready to re-commit with a different message or additional changes.
Undo the Last Commit (Unstage Changes)
Mixed reset — uncommit and unstage, but keep files modifiedbash
1
git reset HEAD~1
Completely Discard the Last Commit
Hard reset — remove the commit and all its changesbash
1
git reset --hard HEAD~1
--hardpermanently discards uncommitted changes. Only use it if you're sure you want to throw away the work. If in doubt, use --soft instead.
Unstage Files
Remove files from staging without losing changesbash
1
# Unstage a specific file
2
git restore --staged myfile.txt
3
4
# Unstage everything
5
git restore --staged .
Discard Local Changes
Throw away modifications to a filebash
1
# Discard changes in a specific file
2
git restore myfile.txt
3
4
# Discard ALL local changes (careful!)
5
git restore .
Fix a Commit Message
Amend the most recent commit messagebash
1
git commit --amend -m "corrected commit message"
Only amend commits that haven't been pushed yet. Amending a pushed commit rewrites history and will cause problems for anyone who already pulled it.
Recover a Deleted Branch
Find and restore a deleted branchbash
1
# Find the commit the branch pointed to
2
git reflog
3
4
# Recreate the branch from that commit
5
git branch recovered-branch abc1234
git reflog is your safety net. It records every HEAD movement for the last 90 days. Even after git reset --hard, you can usually find the lost commit here.
Undo a Pushed Commit (Safely)
Revert creates a new commit that undoes the changesbash
1
git revert HEAD
Revert vs Reset:
Command
What It Does
Safe for Shared Branches?
git revert
Creates a new commit that undoes changes
Yes — doesn't rewrite history
git reset
Moves the branch pointer backwards
No — rewrites history, breaks others
Cherry-Pick a Commit from Another Branch
Apply a specific commit to your current branchbash
1
git cherry-pick abc1234
Undo a Merge (Before Pushing)
Reset to the commit before the mergebash
1
git reset --hard HEAD~1
Undo a Merge (After Pushing)
Revert a merge commit (keep history intact)bash
1
git revert -m 1 <merge-commit-hash>
The -m 1 tells Git which parent to revert to — usually 1 (your branch before the merge).
The "Nuclear" Recovery Tool
When everything is brokenbash
1
# See ALL recent actions
2
git reflog
3
4
# Reset to any previous state
5
git reset --hard HEAD@{5}
Even if you've run git reset --hard, the old commits still exist in the reflog for 90 days. You can almost always recover. The only thing Git truly can't recover is uncommitted, unstaged changes — if you never git add'd it, it's gone.