Choosing Between Reset, Revert, and Restore
Undoing commits in Git has several approaches, each with different trade-offs. git reset --soft HEAD~1 moves HEAD back one commit but keeps changes staged — ideal for re-doing a commit with a better message. git reset --mixed HEAD~1 unstages the changes too. git reset --hard HEAD~1 discards changes entirely — use with extreme caution.
git revert <commit> creates a new commit that undoes the changes — this is the safe option for commits already pushed to a shared branch. It preserves history, so collaborators aren't affected. Never use git reset on commits that others have pulled.
For undoing specific file changes (not whole commits), git restore <file> discards unstaged changes, and git restore --staged <file> unstages changes while keeping them in the working directory. Use git reflog as your safety net — it records every HEAD position and lets you recover from almost any mistake.
Tips
- Not pushed yet? Use
git reset --soft HEAD~1to undo the commit but keep your changes staged. - Already pushed? Use
git revert HEAD— it creates an undo commit without rewriting history. - Force push (last resort): Only force push to branches where you're the only author. Never to main/master.
git reflogshows every HEAD position for 90 days — you can recover reset commits withgit checkout <hash>.