The Git undo cheat sheet: pushed vs not pushed
The wrong undo command can turn a small Git slip into lost work.
Published here · 4 sources · Resume reading
The wrong undo command can turn a small Git slip into lost work. Ask one question first: did this commit leave my laptop?
The pushed test: pushed? revert. Not pushed? reset.
The undo commands
Each one tagged by what it can lose:
1. Staged the wrong file (safe)
git restore --staged app.js2. Committed too soon, not pushed (before push)
git reset --soft HEAD~13. Bad commit already pushed (safe on shared branches)
git revert <sha>4. Throw away your edits (no undo)
git restore app.js5. Committed on main by mistake (only before push, with a clean git status)
git branch feature
git reset --hard HEAD~1
git switch featureUse HEAD~3 if three commits landed. reset --hard wipes uncommitted changes, so stash first.
6. Dropped a stash (rescue)
From the git stash docs:
git fsck --unreachable | grep commit | cut -d\ -f3 | xargs git log --merges --no-walk --grep=WIPNamed it with -m? Remove --grep=WIP.
git stash apply <sha>Every command was run in a throwaway test repo on Git 2.54.
Send this to the friend who reached for a hard reset after a commit was already pushed.
Keep this guide
Filed under Dev tools
Questions about this guide
When should I use revert instead of reset?
Use revert on anything already pushed. It creates a new commit that undoes the old one without rewriting history.
How do I rescue a dropped stash?
Run git fsck to find unreachable commits, grep for WIP if you did not name it, and apply by SHA.
Sources
- Git docs: git-restoregit-scm.com
- Git docs: git-resetgit-scm.com
- Git docs: git-revertgit-scm.com
- Git docs: git-stashgit-scm.com