我不小心说了git rm -r .
。我该如何从中恢复?
我没有答应。
我认为所有文件都被标记为删除,并且也从我的本地结帐中物理删除。
编辑:我可以(如果我知道命令)恢复到最后一次提交。但如果我能撤消git rm -r .
. 因为我不太确定在最后一次提交之后和git rm -r .
.
git reset HEAD
应该这样做。如果您没有任何您关心的未提交更改,那么
git reset --hard HEAD
应该强制将所有内容重置为您的最后一次提交。如果您确实有未提交的更改,但第一个命令不起作用,则使用以下命令保存未提交的更改git stash
:
git stash
git reset --hard HEAD
git stash pop
当我意识到我需要返回其中的一些文件时,我 git-rm'd 了一些文件并在下一次提交之前继续进行更改。如果需要,您可以简单地检查您错过/删除的单个文件,而不是存储和重置:
git checkout HEAD path/to/file path/to/another_file
这使您的其他未提交的更改完好无损,没有变通办法。
要重新获得一些单个文件或文件夹,可以使用以下
git reset -- path/to/file
git checkout -- path/to/file
这将首先重新创建索引条目path/to/file
并重新创建文件,就像上次提交时一样,即HEAD
.
提示:可以将提交哈希传递给两个命令,以从较旧的提交重新创建文件。有关详细信息,请参见git reset --help
和git checkout --help
。
更新:
由于git rm .
删除了工作结帐以及索引中的此目录和子目录中的所有文件,因此您需要撤消这些更改中的每一个:
git reset HEAD . # This undoes the index changes
git checkout . # This checks out files in this and child directories from the HEAD
这应该做你想要的。它不会影响您签出代码或索引的父文件夹。
旧答案不是:
reset HEAD
可以解决问题,并且不会删除您对文件所做的任何未提交的更改。
之后,您需要重复git add
您排队的任何命令。
如果您最终没有上述工作,您可能可以使用此处的建议检索数据:http ://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
撤消 git rm
git rm file # delete file & update index
git checkout HEAD file # restore file & index from HEAD
撤消 git rm -r
git rm -r dir # delete tracked files in dir & update index
git checkout HEAD dir # restore file & index from HEAD
撤消 git rm -rf
git rm -r dir # delete tracked files & delete uncommitted changes
not possible # `uncommitted changes` can not be restored.
Uncommitted changes
包括not staged changes
, staged changes but not committed
.
如果您已提交并推送更改,则可以执行此操作以取回文件
// Replace 2 with the # of commits back before the file was deleted.
git checkout HEAD~2 path/to/file
已经有一些很好的答案,但我可能会建议一种很少使用的语法,它不仅效果很好,而且在你想要的方面非常明确(因此并不可怕或神秘)
git checkout <branch>@{"20 minutes ago"} <filename>
获取列表提交
git log --oneline
例如,稳定提交具有哈希:45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master
我也有同样的情况。就我而言,解决方案是:
git checkout -- .
使用 Git 2.23+(2019 年 8 月),恢复文件(和索引)的正确命令将是使用... git restore
(不是reset --hard
或令人困惑的git checkout
命令)
那是:
git restore -s=HEAD --staged --worktree -- .
或其缩写形式:
git restore -s@ -SW -- .
如果您git rm -r --cached .
在带有未暂存(因此也未提交)的更改的 repo 上执行该命令,您可以使用该命令撤消该操作(从删除中取消暂存)git restore --staged .
所以简而言之,要撤消 git rm -r --cached .
你只需要运行git restore --staged .
我遇到了完全相同的问题:清理我的文件夹、重新排列和移动文件。我输入: git rm 。并按回车;然后感觉我的肠子松了一点。幸运的是,我没有直接输入 git commit -m "" 。
但是,以下命令
git checkout .
恢复了一切,救了我的命。