I messed up my LAST COMMIT
| What happened | Fix it with |
|---|
| Committed too early, want to undo but keep changes | git reset --soft HEAD~1 |
| Committed to wrong branch, want to move commit | git reset --soft HEAD~1 then git stash and switch branches |
| Commit message has a typo | git commit --amend -m "Correct message" |
| Forgot to add a file to the commit | git add forgotten-file<br>git commit --amend --no-edit |
| Want to completely delete last commit (permanent!) | git reset --hard HEAD~1 |
I messed up STAGING (git add)
| What happened | Fix it with |
|---|
| Added a file by accident | git reset HEAD file |
| Added multiple files, want to unstage one | git reset HEAD file-i-dont-want.js |
| Want to see what's staged before committing | git diff --staged |
| Unstage everything but keep changes | git reset |
I messed up WORKING DIRECTORY (unstaged changes)
| What happened | Fix it with |
|---|
| Edited a file and want to undo | git checkout -- file |
| Want to discard all local changes | git checkout -- . |
| Want to remove untracked files | git clean -fd |
| Want to undo changes in multiple specific files | git checkout -- file1.js file2.js |
I messed up BRANCHES
| What happened | Fix it with |
|---|
| Merged by accident | git reset --hard ORIG_HEAD |
| Want to move a commit to another branch | git log (copy hash)<br>Switch to target branch<br>git cherry-pick <hash> |
| Branch name is wrong | git branch -m new-name |
| Deleted a branch by accident | git reflog (find hash)<br>git checkout -b recovered-branch <hash> |
Emergency: I REALLY messed up
| What happened | Fix it with |
|---|
| Need to undo multiple commits | git reset --soft HEAD~3 (undo last 3 commits, keep changes) |
Accidentally did git reset --hard | git reflog → find the commit hash → git reset --hard <hash> |
| Want to revert a pushed commit safely | git revert <commit-hash> (creates new commit that undoes it) |
One-Line Cheatsheet
| Command | What it does | Safe? |
|---|
git status | Shows what's happening | ✅ |
git log --oneline | Shows commit history | ✅ |
git diff | Shows unstaged changes | ✅ |
git checkout -- file | Discard changes in file | ⚠️ |
git reset HEAD file | Unstage file | ✅ |
git reset --soft HEAD~1 | Undo commit, keep changes staged | ✅ |
git reset --hard HEAD~1 | Delete last commit and changes | ❌ |
git commit --amend | Fix last commit | ⚠️ |
git clean -fd | Delete untracked files | ❌ |
Golden Rules
- Always run
git status first - it tells you what's going on
--hard is the nuclear option - it deletes things permanently
reflog is your time machine - if you really screw up, git reflog shows EVERYTHING you've done
- When in doubt,
git stash - temporarily saves your changes so you can try things safely
Pro tip: If you've already pushed to remote, avoid reset and use revert instead
git revert <bad-commit-hash>
This creates a new commit that undoes the bad one - safe for shared branches!