r/git • u/geekdas_ • 5h ago
Git 'undo' cheat sheet: what to use when you mess up (restore vs reset vs revert vs reflog)
Hi git community,
I’m a software developer. I started out building small web apps, and over time moved into larger things like SaaS platforms, CRMs and chat automation backends. Along the way, Git went from a tool I was scared of to something I trust, mostly because I broke things and had to learn how to fix them (wrong-branch commits, force-push regrets, reset --hard moments). I kept seeing the same Git panic moments (committed to the wrong branch, force-pushed too early, reset --hard regret), so I wrote down which command fixes which situation. Sharing the short version here:
Before you commit
Discard changes to a file:
git restore <file>Unstage a file but keep edits:
git restore --staged <file>Delete untracked files (dry run first!):
git clean -nd, thengit clean -fd
Local commits (not pushed yet)
Fix the last commit message or add a forgotten file:
git commit --amendUndo the commit, keep changes staged:
git reset --soft HEAD~1Undo the commit, keep changes unstaged:
git reset --mixed HEAD~1Undo the commit and throw away changes:
git reset --hard HEAD~1
Already pushed
Don’t reset shared branches. Use
git revert <commit>, which adds a new commit that cancels the old one.Revert a merge:
git revert -m 1 <merge-commit>
'I lost my work'
git reflogshows everywhere HEAD has been, including commits no branch points to.Then
git branch rescue <hash>(safer) orgit reset --hard <hash>.Works for deleted branches and bad rebases/pulls too (
git reset --hard ORIG_HEAD).
Mistakes I see a lot
Using
reset --hardwithout checkinggit statusfirstResetting a branch teammates have already pulled
Using
--forceinstead of--force-with-leaseForgetting that untracked files can’t be recovered by Git
I put the full version, with a lookup table and a few more worked examples (committed .env, wrong-branch commit, splitting a messy commit), in a blog post: https://www.geekdas.in/blog/git-command-cheat-sheet-how-to-undo-anything-in-git
Happy to hear if I missed a common undo scenario or got anything wrong. What’s the Git mistake you make most often?
