Undo a Git merge that hasn't been pushed yet

2018-12-31 03:48发布

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?

27条回答
旧时光的记忆
2楼-- · 2018-12-31 04:05

I think you can do git rebase -i [hash] [branch_name] where [hash] is the identifying hash for however far back you want to rewind plus one (or however many commits back you want to go) and then delete the lines for the commits in the editor that you don't want any more. Save the file. Exit. Pray. And it should be rewound. You might have to do a git reset --hard, but it should be good at this point. You can also use this to pull specific commits out of a stack, if you don't want to keep them in your history, but that can leave your repository in a state that you probably don't want.

查看更多
梦该遗忘
3楼-- · 2018-12-31 04:06

If you didn't commit it yet, you can only use

$ git checkout -f

It will undo the merge (and everything that you did).

查看更多
千与千寻千般痛.
4楼-- · 2018-12-31 04:07

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.

查看更多
怪性笑人.
5楼-- · 2018-12-31 04:07

If you want a command-line solution, I suggest to just go with MBO's answer.

If you're a newbie, you might like the graphical approach:

  1. Kick off gitk (from the command line, or right click in file browser if you have that)
  2. You can easily spot the merge commit there - the first node from the top with two parents
  3. Follow the link to the first/left parent (the one on your current branch before the merge, usually red for me)
  4. On the selected commit, right-click "Reset branch to here", pick the hard reset there
查看更多
浮光初槿花落
6楼-- · 2018-12-31 04:09

You could use git reflog to find the previous checkout. Sometimes that's a good state you want to return back to.

Concretely,

$ git reflog
$ git reset --hard HEAD@{0}
查看更多
几人难应
7楼-- · 2018-12-31 04:12

You should reset to the previous commit. This should work:

git reset --hard HEAD^

Or even HEAD^^ to revert that revert commit. You can always give a full SHA reference if you're not sure how many steps back you should take.

In case when you have problems and your master branch didn't have any local changes, you can reset to origin/master.

查看更多
登录 后发表回答