这在很大程度上取决于您所说的“还原”。
暂时切换到其他提交
如果您想暂时回到它,四处闲逛,然后回到自己的位置,您所要做的就是检查所需的提交:
# This will detach your HEAD, that is, leave you with no branch checked out:
git checkout 0d1d7fc32
或者,如果您想在该位置进行提交,请继续并在该位置创建一个新分支:
git checkout -b old-state 0d1d7fc32
要回到原来的位置,只需再次检查您所在的分支即可。(如果进行了更改,则像往常一样在切换分支时必须进行适当的处理。可以重置以将其丢弃;可以隐藏,签出,隐藏弹出以随身携带它们;可以提交如果您要在那儿有分支,请把它们送到那儿。)
硬删除未发布的提交
另一方面,如果您想真正摆脱之后的所有工作,则有两种可能性。一个,如果您尚未发布任何这些提交,只需重置:
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to.
如果您搞砸了,您已经放弃了本地更改,但是至少可以通过重新设置回到原来的状态。
用新提交撤消已发布的提交
另一方面,如果您已经发布了作品,则可能不想重置分支,因为那样可以有效地重写历史记录。在这种情况下,您确实可以还原提交。使用Git,还原具有非常特殊的含义:使用反向补丁创建提交以将其取消。这样,您就不会重写任何历史记录。
# This will create three separate revert commits:
git revert a867b4af 25eee4ca 0766c053
# It also takes ranges. This will revert the last two commits:
git revert HEAD~2..HEAD
#Similarly, you can revert a range of commits using commit hashes:
git revert a867b4af..0766c053
# Reverting a merge commit
git revert -m 1 <merge_commit_sha>
# To get just one, you could use `rebase -i` to squash them afterwards
# Or, you could do it manually (be sure to do this at top level of the repo)
# get your index and work tree into the desired state, without changing HEAD:
git checkout 0d1d7fc32 .
# Then commit. Be sure and write a good message describing what you just did
git commit
该手册git-revert
页实际上在其说明中涵盖了很多内容。另一个有用的链接是git-scm.com讨论git-revert的部分。
如果您决定根本不希望还原,则可以还原该还原(如此处所述),也可以还原到还原之前的状态(请参阅上一节)。
在这种情况下,您可能还会发现此答案很有用:
如何将HEAD移回先前的位置?(独立头)