如何将Git存储库恢复为以前的提交

时间 2010-11-07
阅读 4639955
点赞 6374
收藏 2960
连接crazy-serb

如何从当前状态恢复到某个提交时创建的快照?

如果我这样做git log,然后我得到以下输出:

$ git log
commit a867b4af366350be2e7c21b8de9cc6504678a61b

Author: Me <me@me.com>
Date:   Thu Nov 4 18:59:41 2010 -0400

blah blah blah...

commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4
Author: Me <me@me.com>
Date:   Thu Nov 4 05:13:39 2010 -0400

more blah blah blah...

commit 0766c053c0ea2035e90f504928f8df3c9363b8bd
Author: Me <me@me.com>
Date:   Thu Nov 4 00:55:06 2010 -0400

And yet more blah blah...

commit 0d1d7fc32e5a947fbd92ee598033d85bfc445a50
Author: Me <me@me.com>
Date:   Wed Nov 3 23:56:08 2010 -0400

Yep, more blah blah.
如何从11月3日恢复到提交,即提交

0d1d7fc

✅ 被采纳的答案

这很大程度上取决于你所说的“还原”。

临时切换到其他提交

如果你想暂时回到原来的状态,那就绕过去,然后回到原来的状态,你所要做的就是检查一下你想要的承诺:

# 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,revert有一个非常具体的含义:使用reverse补丁创建一个commit来取消它。这样你就不会重写任何历史。

# 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. this git-scm.com section discussing git-revert如果您决定根本不想还原,可以还原还原(如此处所述)或重置回还原之前的状态(请参阅上一节)。

在这种情况下,您也会发现这个答案很有用:


How to move HEAD back to a previous location? (Detached head)

👍 8211