Git revert merge: While working on projects and managing them on Version Control Systems like Git, occasionally you can get yourself into situations where you merge your changes, commit them, and even push them together to the remote repository, but after doing that, you realize that this recent merge had an issue with it.
In such a case, you will likely find a way to get your main branch back to its stable state. This is where you need to undo or revert your merge in Git.
There are two states where this problem can be handled:
- You are still in the merging process.
- You are done with the merging process.
If your case falls in the first category, you can revert the merge with the following command:
git merge --abort
This way, Git will clean up everything for you and will nicely abort your merge commit. Thus, the branch will get back to its previous stable state.
However, if you have already committed your merge, then there is no restoring point. The only solution is to revert the merging commit. Let’s see how you can do it.
Table of Contents
Revert Merge After Committing
Step#01: Get Out of the Main Branch
The first step is to get yourself out of the branch affected by the commit since this is the branch that will be under a few changes now.
Use the following command to get yourself out of the branch:
git checkout <branchName>
Step#02: Find the Last Commit Hash Number
git log --oneline
Step#03: Revert the Traced Commit
Finally, you have the hash number of the commit message in which you made the wrong merge. Use the following command to undo it.
git revert -m 1 [commit-hash]
Let’s understand this command. Here:
- -m: This flag represents the mainline branch, i.e., the branch into which the merge is performed mainly. Remember, in a merge operation, two branches are involved, so it has two parent commits, one from each branch. So, you need to decide which parent branch is going to be the mainline or the base branch you merged into.
- Then you are passing a 1. This points to the branch that you just checked out when you began the reverting process. (Passing 2 in place of 1 will point out to the other branch involved in merge but is not the one being merged in)
Conclusion
Reverting your Git merges is a messy, confusing and unclear thing. It results in generating unclear Git history and disturbs the workflow. When your project development increases with time, it becomes more difficult to manage these issues, and every developer wants to avoid such a situation.
But in case you are trapped with the issue, follow this guide, and hopefully, you will be able to resolve the error.