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.
Undoing a Merge in Tower
In case you are using the Tower Git client, undoing a merge is really simple: just press CMD+Z afterwards and Tower will undo the merge for you!
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 to git reset, where we effectively "remove" a commit from the history. That's also the reason why git 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 using git revert, however, we have to specify the actual merge commit's hash.