Git

Undo a Git Merge That Hasn’t Been Pushed Yet

Developers work on various branches for different features while working on a large development project. After completing work on one branch, they merge or combine it with the main project. However, sometimes, you may merge the wrong branch with the main branch. In this situation, Git allows you to undo the merge operation.

This write-up is about undoing an unpushed Git merge.

How to Undo/Revert a Merge in Git That Has Not Been Pushed?

To undo/revert an unpushed Git merge, different options can be used with the “git reset” command, such as:

Method 1: Undo a Git Merge Using “git reset –hard HEAD~1” Command

First, view the merge commit by checking the commit history:

$ git log --oneline

In the below screenshot, it can be seen that the HEAD is pointing to the latest merge commit:

Then, run the below-stated command to undo the Git merge:

$ git reset --hard HEAD~1

Here, the “–hard” option is used to discard all changes in the working tree, and the “HEAD~1” option is utilized to undo the latest commit:

Next, verify the changes by viewing the commit history:

$ git log --oneline

It can be observed that the HEAD is now pointing to the previous commit which means the merge operation has been reverted:

Method 2: Undo a Git Merge Using “git reset –merge HEAD~1” Command

First, display the commit history to view the merge commit:

$ git log --oneline

Next, undo the merge by executing the following command:

$ git reset --merge HEAD~1

Lastly, view the commit history to verify changes:

$ git log --oneline

As you can see, the merge operation has been reverted successfully:

We have explained the methods to undo a Git merge that has not been pushed yet.

Conclusion

To undo a Git merge that has not been pushed yet, you can use different options with the “git reset” command, such as “–hard” or “–merge” options. However, the “–hard” option removes the uncommitted changes in the working tree, and the “–merge” option keeps the uncommitted changes. This article described the procedure to undo the Git merge that has not been pushed.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.