Git: Revert a Merge

If you merge a branch in to another, and for whatever reason decide you want to undo the merge, there are some ways to do this with Git.

The solution to this is simpler if you haven't yet pushed the changes to a remote repo, and if you have then you'll likely have to rely on something like git revert instead of the solution proposed below. For this short article I'll explain how you can undo a Git merge that hasn't been pushed yet.

The first step would be to use reflog to find the commit right before the merge:

$ git reflog

Executing this on your repo will return a list of recent commits, including their abbreviated hashes, distance from HEAD, and description. It will look something like this:

$ git reflog
8135d07 HEAD@{0}: commit (merge): Merge branch local/bug-34 into local/master
03979c8 HEAD@{1}: commit: Added support for query params
9f7a993 HEAD@{2}: commit (initial): Initial commit

Once you find the commit that you want to revert back to, use the reset command, similar to what we did when reverting to a previous commit, which is essentially what we're doing here:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

$ git reset --hard <commit-hash>

So in the above example we might want to revert to the commit with the message "Added support for query params", which we'd do like this:

$ git reset --hard 03979c8

The --hard option will revert the code in the tree, staging, and working copies. If you don't want to lose any local changes you've made then --merge or --mixed may be better options for you.

If the commit you want to get back to is only one behind HEAD, then you can instead use ORIG_HEAD as a shortcut in the reset command:

$ git reset --hard ORIG_HEAD

This will be easier in some cases since you won't have to use reflog to find the commit hash. ORIG_HEAD is roughly equivalent to HEAD@{1}, so only use it if you're wanting to revert back a single commit.

Note: Once you have pushed changes to a remote repo, it is not recommended to revert commits in this way since you'd be erasing history. In that case I'd recommend using the git revert command, which will undo the unwanted changes as a separate commit.

Last Updated: June 11th, 2019
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms