我不小心在本地主分支上运行了gitmergesome_other_branch。我还没有将更改推送给origin master。如何撤消合并?


合并后,git状态显示:

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

我如何撤销所有这些提交?


当前回答

如果没有冲突和合并完成,则:

  git reset --hard HEAD~1

如果在执行合并时发生冲突,则中止将使您退出最近的合并更改:

git merge --abort

或者如果您想恢复到特定的提交id。

 git reset --hard <commit-id>

其他回答

假设您的本地主机不领先于源/主机,您应该能够

git reset --hard origin/<branch-name>

因此,假设您在master上执行了此操作,那么您的本地master分支看起来应该与origin/master相同。

好吧,这里的其他人给我的答案很接近,但没用。这是我所做的。

正在执行此操作。。。

git reset --hard HEAD^
git status

…给了我以下状态。

# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.

然后,我不得不多次输入相同的git重置命令。每次我这样做时,信息都会改变一个,如下所示。

> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 3 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 1 and 3 different commit(s) each, respectively.
> git reset --hard HEAD^
HEAD is now at [...truncated...]
> git status
# On branch master
# Your branch is behind 'origin/master' by 3 commits, and can be fast-forwarded.

此时,我看到状态消息发生了变化,所以我尝试进行git拉动,这似乎奏效了:

> git pull
Updating 2df6af4..12bbd2f
Fast forward
 app/views/truncated |    9 ++++++---
 app/views/truncated |   13 +++++++++++++
 app/views/truncated |    2 +-
 3 files changed, 20 insertions(+), 4 deletions(-)
> git status
# On branch master

长话短说,我的命令归结为:

git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git reset --hard HEAD^
git pull

如果您正在合并过程中,您可以随时中止它

git merge --abort

如果你还没有提交,你只能使用

$ git checkout -f

它将撤消合并(以及您所做的一切)。

到了这个问题,我们也希望恢复到与原点匹配(即,在原点之前没有提交)。进一步研究发现,有一个重置命令正是针对这一点:

git重置--硬@{u}

注意:@{u}是origin/master的简写。(当然,您需要远程存储库才能实现这一点。)