How to Revert a Merge Commit Already Pushed to the Remote Branch in Git

Suppose that you have merged two branches and pushed the merged commit. After that, you find out that the merged commit should be reverted. Here, we will assist you in doing that.

Steps to reverting merge commit pushed to the remote

Let's suppose that you are on the branch, on which the commit of the merge is.

Viewing history

It is known that, in Git, the merge commits have two parent commits, and after running the git log command, in its output, you can see the parent commit hashes of the merge commit.

commit 4f937c683929b08379097828c8a04350b9b8e45 
Merge: 7676ee5 8c4b635 
Author: SSL 
Date: THU JAN 21 19:30:24 2020 +0100 Merge branch 'gh-pages' Conflicts: README

Reverting to the commit

As, in this case, you want to revert the merge commit, you can't act the same as while reverting ordinary commits. Here, you need to run the git revert command with the -m 1|2 option:

git revert 8f937c6 -m 1

It will give you the tree as it was in:

  7676ee5

With -m 1, you instruct Git to revert to the first parent of the merge commit. If you use -m 2 instead of the -m 1 option, Git will revert to the second parent of the merge commit.

In case of -m 2, the tree will be reinstated like it was in:

8c4b635 

For the better understanding of parent IDs, you need to run:

git log 7676ee5

Or:

git log 8c4b635

The git revert Command

The git revert is mainly used for undoing changes to a commit history of the git repository. This command takes a particular commit, but it doesn’t move ref commits to that commit. The git revert operation takes the particular commit, inverses its changes, and generates a new “revert commit”.

But you should also consider that git revert can undo a single commit and will not return to the previous state of your project. That operation can be done with the help of the git reset command.

The git log Command

Whenever it is necessary to list and filter your project history or to search for specific changes, you can turn to the git log command. It will show you the committed snapshots. Note that this command can work merely on the committed history, in comparison with git status, which controls the working directory, as well as the staging area.