Matt Huggins Matt Huggins - 8 months ago 41
Git Question

Undo a Git merge that hasn't been pushed yet?

Within my master branch, I did a

git merge some-other-branch
locally, but never pushed the changes to origin master. I didn't mean to merge, so I'd like to undo it. When doing a
git status
after my merge, I was getting this message:

# On branch master
# Your branch is ahead of 'origin/master' by 4 commits.

Based upon some instructions I found, I tried running

git revert HEAD -m 1

but now I'm getting this message with
git status

# On branch master
# Your branch is ahead of 'origin/master' by 5 commits.

I don't want my branch to be ahead by any number of commits. How do I get back to that point?


With git log check which commit is one prior the merge. Then you can reset it using:

git reset --hard commit_sha

There's also another way

git reset --hard HEAD~5

will get you back 5 commits.

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 tips is to use the --merge switch instead of --hard, it doesn't reset files unnecessarily:


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).