Git: How to reset after merging?

2019-03-20 15:07发布

I've merged a master branch from a friend's repository into my working directory into branch_a using:

git pull my_friend master

I've discovered that the merged version has errors. To continue development I would like to revert to my last commit before the merge.
I tried:

git reset --hard HEAD

But that brought me back to the state right after the merge. (does pull command commit?!)
I also tried:

git revert HEAD

but received the following error:

fatal: Commit 2d72d8f367b987d8c16f5cb1a543a6886acdcf83 is a merge but no -m option was given.

What should I do?

3条回答
Ridiculous、
2楼-- · 2019-03-20 15:11

HEAD refers to the current commit (generally the tip of the currently checked-out branch). You've already committed your merge, so HEAD is pointing to the merge commit. If you want to get back to the commit before it, use:

git reset --hard HEAD^

The ^ means "first parent of"; for a regular commit it's the only parent, and for a merge commit it's the commit you had checked out when you merged (i.e. the prior tip of the branch you merged into).

And of course, if you ever get really lost, just open up gitk, and either copy/paste the SHA1 of the commit you want to reset to (git reset --hard SHA1) or just right click on it and reset within gitk.

By the way, revert doesn't mean what you think it does (it sounds like you're using it in an svn way, maybe? but I've never used svn). git revert is used to create a commit which cancels out (reverts) a previous commit, by applying the reverse diff. You use it when you want to undo a single previous commit which has already been published.

查看更多
爷、活的狠高调
3楼-- · 2019-03-20 15:19

does pull command commit?

Yes, it does. Pull is a wrapper over fetch and merge. If you want to see other's changes before merging, you can just fetch

查看更多
霸刀☆藐视天下
4楼-- · 2019-03-20 15:25

After the pull, HEAD has been moved to the latest commit, which is the merge commit bringing the two branches together, not the commit that you last worked on. So this is why reset HEAD won't change anything.

revert HEAD isn't what you want to do either, because that is attempting to create a new commit reverting the changes of the merge commit. (This is why you see an error; you can't revert a merge commit without telling git which of the two parent commits you want to return to.)

I think what you want is:

git reset [--hard] HEAD^

which will reset to the commit before the merge commit.

查看更多
登录 后发表回答