How to Revert a Merge Commit Already Pushed to the Remote Branch in Git
On this page, you will find a short tutorial on how to revert a merge commit that is already pushed to the remote branch. Just follow the commands below.
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: READMEReverting 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
git revert 8f937c6 -m 1It will give you the tree as it was in:
7676ee5With <kbd class="highlighted">-m 1</kbd>, you instruct Git to revert to the first parent of the merge commit. If you use <kbd class="highlighted">-m 2</kbd> instead of the <kbd class="highlighted">-m 1</kbd> option, Git will revert to the second parent of the merge commit.
In case of <kbd class="highlighted">-m 2</kbd>, the tree will be reinstated like it was in:
8c4b635 For the better understanding of parent IDs, you need to run:
git log
git log 7676ee5Or:
git log
git log 8c4b635The 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 <kbd class="highlighted">git revert</kbd> operation takes the particular commit, inverses its changes, and generates a new “revert commit”.
But you should also consider that <kbd class="highlighted">git revert</kbd> 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.