• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (deprecated)
You are here: Home / Dev Tips / Revert Merge Commit

Revert Merge Commit

Last updated on September 14, 2023 by Sal Ferrarello

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 C
|/  
* 2b3a38b B
* ec6a2c7 A

If you run git revert HEAD, does Git revert to 163fe29 or to 5d408f9?

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 5d408f9). 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 C
|/  
* 2b3a38b B
* ec6a2c7 A

The state of HEAD (b35e2ac) will now be identical to before the merge commit (5d408f9 C).

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 Merge section on How to Undo a Merge in Git
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Filed Under: Computing, Dev Tips, Solution Tagged With: Git, revert

Reader Interactions

Comments

  1. Damodar says

    June 29, 2023 at 10:27 am

    How can we undo all parent commits of amerge commit, using git revert

    Reply
    • Sal Ferrarello says

      June 29, 2023 at 1:17 pm

      If I understand correctly, it sounds like you want to use `-m 1` in your revert command as described in the “Revert to Before the Merge Commit” section above.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in