Git Commit Undo Guide
When to Use
You've already run git commit and now want to undo it. Which command to use depends on two questions:
- Has this commit already been pushed to the remote?
- Do you still want to keep the local code changes?
Check Current State First
git status -sb
git log --oneline --decorate -5
git branch -vv
git status -sb-- quickly see the current branch and ahead/behind status.git log --oneline --decorate -5-- confirm which commit you actually want to undo.git branch -vv-- help determine whether the current branch is already tracking a remote branch.
Recommended Commands
| Situation | Recommended Command | Result |
|---|---|---|
| Commit not pushed, want to keep as "staged" | git reset --soft HEAD~1 | Commit disappears, changes remain in staging |
| Commit not pushed, want to keep as "unstaged" edits | git reset --mixed HEAD~1 | Commit disappears, changes stay in working directory |
| Commit not pushed, don't want the code either | git reset --hard HEAD~1 | Commit and local changes both discarded |
| Commit already pushed, or others may be building on it | git revert <commit> | Creates a new reverse commit, doesn't rewrite history |
git reset HEAD~1 defaults to --mixed.
Common Scenarios
Undo the Last Local Commit but Keep the Code
git reset --soft HEAD~1
Useful when you just committed and realize the message is wrong or files are missing, and you want to recommit.
Undo the Last Local Commit and Return to Editing State
git reset --mixed HEAD~1
Undo the Last 3 Local Commits
git reset --soft HEAD~3
If you've already pushed to a "personal branch maintained only by you" and explicitly want to rewrite remote history, you can follow up with:
git push --force-with-lease origin $(git branch --show-current)
Undo a Commit That's Already Been Pushed
git revert <commit>
For more details, see Git revert Guide.
Risks and Boundaries
git resetmoves the current branch pointer -- it counts as rewriting history.git reset --harddirectly overwrites the working directory and staging area -- highest risk.- On shared branches, public branches, or history others may have already pulled, don't default to
resetfollowed by force push -- prefergit revert. - If you misused
reset, in many cases you can still recover local history withgit reflog.
Related Commands
git reflog
git commit --amend
git revert HEAD
git push --force-with-lease origin <branch>