如何恢复在Git中丢失的提交?


Answers:


586

git reflog是你的朋友。在该列表中找到要提交的提交,然后可以将其重置(例如:)git reset --hard e870e41

(如果您不提交更改,则可能会遇到麻烦-提早提交,并经常提交!)


5
看一看git log HEAD@{1}。如果这看起来像正确的一系列提交,则可以git reset HEAD@{1}
2012年

4
只有将代码暂存(使用git add),它们才会保存在git中,并且可以使用像这样的命令轻松找到git fsck --lost-found
Landys

2
在重新定基时不小心遗漏了我应该保留的提交。这完全使我免除了重做几个小时的工作。
约瑟夫

27
这救了我一命。
Lutaaya Huzaifah Idris

6
这节省了我的理智:D
Frank Fajardo

117

在回答之前,让我们添加一些背景,解释一下这HEAD是什么。

First of all what is HEAD?

HEAD只是对当前分支上当前提交(最新)的引用。在任何给定时间(除外)
只能有一个。HEADgit worktree

的内容HEAD存储在内部.git/HEAD,它包含当前提交的40个字节的SHA-1。


detached HEAD

如果您不在最新的提交上-这意味着HEAD指向历史上的先前提交,则称为detached HEAD

在此处输入图片说明

在命令行上,它看起来像这样-SHA-1而不是分支名称,因为HEAD并不指向当前分支的尖端:

在此处输入图片说明

在此处输入图片说明


有关如何从分离的HEAD中恢复的几种选择:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

这将签出指向所需提交的新分支。
该命令将签出给定的提交。
此时,您可以创建一个分支并从此开始工作。

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

您也可以随时使用reflog
git reflog 将显示任何更新的更改,HEAD并签出所需的reflog条目,将HEAD后退设置为此提交。

每次修改HEAD时,都会在 reflog

git reflog
git checkout HEAD@{...}

这将使您回到所需的提交

在此处输入图片说明


git reset --hard <commit_id>

将“ HEAD”“移动”回所需的提交。

# 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 2.7开始),您也可以使用git rebase --no-autostash

git revert <sha-1>

“撤消”给定的提交或提交范围。
reset命令将“撤消”在给定提交中所做的任何更改。
带有撤消补丁的新提交将被提交,而原始提交也将保留在历史记录中。

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

该模式说明了哪个命令可以执行什么操作。
如您所见,reset && checkout修改HEAD

在此处输入图片说明


2
先生,您是英雄吗
dylanh724 '18 -10-23

4
那只是节省了我很多时间的工作。我使用“ git reflog --date = iso”来查看每个条目的日期/时间,因为没有时间戳我无法确定。
MetalMikester,

1
对我来说,git reset --hard <commit_id>删除HEAD工作正常!+1用于图形表示!!。
reverie_ss

只需提及:如果您知道分支名称:git reflog <branchname>可能会非常有用,因为您看到的只是一个分支的更改。
Markus Schreiber

35

获取已删除提交的另一种方法是使用git fsck命令。

git fsck --lost-found

这将输出类似于最后一行的内容:

dangling commit xyz

我们可以使用reflog其他答案中的建议来检查它是否是同一提交。现在我们可以做一个git merge

git merge xyz

注:
我们不能让犯回来fsck,如果我们已经运行一个git gc命令,它会删除提及悬挂承诺。


3
如果您最近没有指向所涉及的提交(例如,当您获取分支然后在其他地方意外重置该分支时),这是唯一可行的答案。
TamaMcGlinn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.