How to Undo Almost Anything in Git
Git is Forgiving
One of Git's strengths is how hard it makes it to lose data. Almost every operation can be undone — if you know which command to use.
Fix the Last Commit
**Wrong message?** Use amend to edit it:
git commit --amend -m "Correct message"
**Forgot a file?** Stage it, then amend:
git add forgotten-file.ts
git commit --amend --no-edit
Unstage a File
Accidentally ran `git add .` and want to unstage?
git restore --staged file.ts
# or the classic way:
git reset HEAD file.ts
Discard Local Changes
Revert a file back to the last committed state:
git restore file.ts
# or:
git checkout -- file.ts
Undo a Commit (Local)
If the commit hasn't been pushed yet, use reset:
# Keep changes staged:
git reset --soft HEAD~1
# Keep changes in working directory (unstage):
git reset --mixed HEAD~1
# Discard changes entirely:
git reset --hard HEAD~1
Undo a Commit (Pushed)
For commits already pushed, use revert — it creates a new commit that reverses the changes:
git revert HEAD
Recover a Deleted Branch
The reflog records every HEAD movement:
git reflog
# Find the commit hash, then:
git branch recovered-branch <hash>
Golden Rule
Never rebase or force-push commits that others have based work on. Use revert instead — it's safer and preserves collaboration history.