Git revert Guide
When to Use
When a commit has already been pushed to the remote, or you don't want to rewrite public history, prefer git revert.
Its approach is not "delete the old commit" but "generate a new reverse commit to cancel out the old one."
Check Current State First
git status
git log --oneline --decorate -5
- Keep the working directory clean before running
revert-- it makes conflicts easier to see. - Confirm the commit hash you want to undo -- don't operate from memory alone.
Recommended Commands
| Scenario | Recommended Command | Result |
|---|---|---|
| Undo the last commit | git revert HEAD | Creates a new reverse commit |
| Undo a specific commit | git revert <commit> | Preserves history, appends a revert record |
| Combine multiple reverts into one commit | git revert --no-commit <commit1> <commit2> | Apply reverse changes first, then commit manually |
| Undo a merge commit | git revert -m 1 <merge-commit> | Requires explicitly specifying the mainline parent |
Common Scenarios
Undo the Last Commit Just Pushed
git revert HEAD
git push origin $(git branch --show-current)
Undo an Earlier Bad Commit
git log --oneline
git revert a1b2c3d
Combine Multiple Bad Commits into One Revert
git revert --no-commit <commit1> <commit2>
git commit -m "Revert problematic changes"
Undo a Merge Commit
git revert -m 1 <merge-commit>
-m 1 typically means keep the mainline from the 1st parent commit. If you're not clear about the parent commit relationships, don't execute this rashly.
Risks and Boundaries
git revertdoes not delete the original commit -- it only adds a new commit with opposite changes.- If the target commit and current code have diverged significantly,
revertmay also produce conflicts. - Undoing merge commits is more error-prone than undoing regular commits -- you must understand the mainline parent first.
- If the commit hasn't been pushed and no one depends on it,
resetfrom Commit Undo Guide is often more direct.
Related Commands
git show <commit>
git revert HEAD
git revert --no-commit <commit1> <commit2>
git log --oneline --decorate -10