Undo a Git merge that hasn't been pushed yet

ID : 74

viewed : 239

Tags : gitundogit-mergegit

Top 5 Answer for Undo a Git merge that hasn't been pushed yet

vote vote

93

With git reflog check which commit is one prior the merge (git reflog will be a better option than git log). Then you can reset it using:

git reset --hard commit_sha 

There's also another way:

git reset --hard HEAD~1 

It will get you back 1 commit.

Be aware that any modified and uncommitted/unstashed files will be reset to their unmodified state. To keep them either stash changes away or see --merge option below.


As @Velmont suggested below in his answer, in this direct case using:

git reset --hard ORIG_HEAD 

might yield better results, as it should preserve your changes. ORIG_HEAD will point to a commit directly before merge has occurred, so you don't have to hunt for it yourself.


A further tip is to use the --merge switch instead of --hard since it doesn't reset files unnecessarily:

git reset --merge ORIG_HEAD 

--merge

Resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

vote vote

85

Assuming your local master was not ahead of origin/master, you should be able to do

git reset --hard origin/master 

Then your local master branch should look identical to origin/master.

vote vote

80

See chapter 4 in the Git book and the original post by Linus Torvalds.

To undo a merge that was already pushed:

git revert -m 1 commit_hash 

Be sure to revert the revert if you're committing the branch again, like Linus said.

vote vote

62

It is strange that the simplest command was missing. Most answers work, but undoing the merge you just did, this is the easy and safe way:

git reset --merge ORIG_HEAD 

The ref ORIG_HEAD will point to the original commit from before the merge.

(The --merge option has nothing to do with the merge. It's just like git reset --hard ORIG_HEAD, but safer since it doesn't touch uncommitted changes.)

vote vote

54

With newer Git versions, if you have not committed the merge yet and you have a merge conflict, you can simply do:

git merge --abort 

From man git merge:

[This] can only be run after the merge has resulted in conflicts. git merge --abort will abort the merge process and try to reconstruct the pre-merge state.

Top 3 video Explaining Undo a Git merge that hasn't been pushed yet

Related QUESTION?