How to revert a merge in Git

I merge a branch, say b1, from another branch, say b2. Both b1 and b2 have some commits.

Say,

b1: c1 --->  c2 ---> c3
b2: c1 --->  c4 ---> c5

Now, if I merge b2 to b1 and there is no conflicts, b1’s history includes b2’s commits (c4, c5).

How to revert this merge in Git?

You can revert/undo the merge (a successful one as in the question) by

$ git reset --hard ORIG_HEAD

But be aware that running git reset --hard ORIG_HEAD will let you go back to where you were, but it will discard your local changes, which you do not want. git reset --merge keeps your local changes.

Two more examples from the git reset man page:

Undo a merge or pull

       $ git pull                         (1)
       Auto-merging nitfol
       CONFLICT (content): Merge conflict in nitfol
       Automatic merge failed; fix conflicts and then commit the result.
       $ git reset --hard                 (2)
       $ git pull . topic/branch          (3)
       Updating from 41223... to 13134...
       Fast-forward
       $ git reset --hard ORIG_HEAD       (4)

   1. Try to update from the upstream resulted in a lot of conflicts; you were not ready to spend a lot of time merging right now, so you decide to do that later.
   2. "pull" has not made merge commit, so "git reset --hard" which is a synonym for "git reset --hard HEAD" clears the mess from the index file and the working tree.
   3. Merge a topic branch into the current branch, which resulted in a fast-forward.
   4. But you decided that the topic branch is not ready for public consumption yet. "pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD, so
   resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

Undo a merge or pull inside a dirty working tree

       $ git pull                         (1)
       Auto-merging nitfol
       Merge made by recursive.
        nitfol                |   20 +++++----
        ...
       $ git reset --merge ORIG_HEAD      (2)

   1. Even if you may have local modifications in your working tree, you can safely say "git pull" when you know that the change in the other branch does not overlap with them.
   2. After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to
   where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.
Leave a Reply

Your email address will not be published. Required fields are marked *