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 server, 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
Table of Contents
Revert Merge After Committing
Step#01: Get Out of the Main Branch
git checkout <branchName>
Step#02: Find the Last Commit Hash Number
git log --oneline
Step#03: Revert the Traced Commit
git revert -m 1 [commit-hash]
- -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)