Typically a Git commit has exactly one parent, however a Git merge commit has two parents (see A Commit with Two Parents). The problem this creates with Git revert, is it is unclear which commit we want to revert to.
* 154382e (HEAD -> main) Merge branch 'feat/d' into main |\ | * 163fe29 (feat/d) D * | 5d408f9 (feat/c) C |/ * 2b3a38b B * ec6a2c7 A
If you run
git revert HEAD, does Git revert to
163fe29 or to
Revert to Before the Merge Commit
Literally every time I have reverted a Git Merge commit I want to go back to the commit before the merge commit (in this case
2b3a38b). To get this behavior we pass
-m 1 to Git revert.
git revert -m 1 HEAD
After this command, your history will look something like
* b35e2ac (HEAD -> main) Revert "Merge branch 'feat/d' into main" * 154382e Merge branch 'feat/d' into main |\ | * 163fe29 (feat/d) D * | 5d408f9 (feat/c) C |/ * 2b3a38b B * ec6a2c7 A
The state of HEAD (
b35e2ac) will now be identical to before the merge commit (
When working with Git and you want to revert a merge commit, you need to indicate which parent commit you want to revert to.
Further Reading on Reverting Merge Commits
- How to revert a merge commit that’s already pushed to remote branch?
- See the
How to Undo a Pushed Mergesection on How to Undo a Merge in Git