How to Undo a Merge in Git
Merging is the process of integrating another branch into your current HEAD branch. (Feel free to check out our git merge Command Overview if you want to learn more about merge in general.)
In this short article, we'll discuss how to undo a merge in Git!
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
Using git reset to Undo a Merge
One of the best aspects about Git is that you can undo virtually anything. And, luckily, a merge is no exception! You can use the git reset
command to return to the revision before the merge, thereby effectively undoing it:
$ git reset --hard <commit-before-merge>
If you don't have the hash of the commit before the merge at hand, you can also use the following variation of the command:
$ git reset --hard HEAD~1
This way, using "HEAD~1", you're telling Git to go back to the commit before the current HEAD revision — which should be the commit before the merge!
Please note that, in both cases, we need to use the "--hard" option. This means that any local changes in your Working Copy will be discarded; if you have valuable uncommitted changes, be sure to use git stash
before.
Tip
Undoing a Merge in Tower
In case you are using the Tower Git client, undoing a merge is really simple: just press CMD+Z (or CTRL+Z on Windows) afterwards and Tower will undo the merge for you!
In Tower, you can easily revert nearly everything using this convenient keyboard shortcut.
How to Undo a Pushed Merge
The example from above is useful when you have NOT already pushed the merge to a remote repository. In such a case, when you've already shared the merge commit with your colleagues on a remote, you should consider a different solution.
$ git revert -m 1 <merge-commit-hash>
Let's take a closer look at what this command will do:
git revert
will make sure that a new commit is created to revert the effects of that unwanted merge. This is in contrast togit reset
, where we effectively "remove" a commit from the history. That's also the reason whygit revert
is a better solution in cases where you've already pushed to a remote.- The
-m 1
option tells Git that we want to keep the parent side of the merge (which is the branch we had merged into). - Finally, also make sure to provide the correct commit hash: for the
git reset
example above, we had to provide the commit before the merge; when usinggit revert
, however, we have to specify the actual merge commit's hash.
Learn More
- Check out the chapter Merging Changes in our free online book
- More frequently asked questions about Git & version control