How to Undo Merge in Git

Azhar Bashir Khan Feb 02, 2024
How to Undo Merge in Git

In this tutorial, we will see about undoing a merge in Git.

In Git, we merge one branch with another to integrate changes from the other branch into the HEAD of the current branch.

Sometimes, we may wish to undo this merging. We can use the Git command git reset to undo a git merge.

We will now illustrate this with an example.

Using the git reset to Undo a Merge in Git

Suppose we have merged a branch viz. feature1 with the main branch to integrate the changes from that branch into the main branch.

Now, we decide to undo this merge. We can use git reset for this.

First, we need to find the commit sha that is before the merge from the log in Git. For this, we can use the git log command.

We will execute the git log command as follows.

$ git log --oneline
0e25143 Merge branch 'feature1'
23ad9ad Add the initial code base

We can see that the 0e25143 is the commit sha of the merge from feature1 branch into the main branch. The 23ad9ad is the commit sha of the commit before merging the branch feature1.

We will use the git reset command with the --hard option to reset the main branch to the state before the merge.

The syntax of the git reset command is below.

git reset --hard commit_sha_before_merge

We will now execute the git reset as follows.

$ git reset --hard 23ad9ad

Thus, we have now undone the merge (i.e.) reset the HEAD of the current branch viz. main to the commit before the merge.

Please note that any uncommitted changes or not stashed changes will be lost after executing the git reset command given above.

We can also use the git reset command as follows, especially if the last commit is of the merge.

$ git reset --hard HEAD~1

It resets the HEAD of the current branch by one commit.

Similarly, we can do as follows too.

$ git reset --hard ORIG_HEAD

The ORIG_HEAD points to the commit before the merge takes place.

A safer option is to use the --merge option with git reset as follows.

$ git reset --merge ORIG_HEAD

The --merge option with the git reset command causes to reset the index and update the files that are different between the commit and the HEAD; but it will keep the changes of the files that are different between the index and the working tree (i.e.) the changes that have not been added to index yet.

Related Article - Git Reset

Related Article - Git Merge