如何恢复“git rm -r。”?

问题描述 投票:340回答:11

我不小心说qazxsw poi。我该如何从中恢复?

我没有承诺。

我认为所有文件都标记为删除,并且还从我当地的结帐中删除。

编辑:我可以(如果我知道命令)恢复到最后一次提交。但如果我能撤消git rm -r .,那将会好得多。因为我不确定在最后一次提交之后和git rm -r .之前我做了什么。

git git-rm
11个回答
429
投票
git rm -r .

应该这样做。如果您没有任何您关心的未提交更改,那么

git reset HEAD

应该强行将所有内容重置为上一次提交。如果您确实有未提交的更改,但第一个命令不起作用,则使用git reset --hard HEAD 保存未提交的更改:

git stash

1
投票

我有一个相同的情况。在我的情况下,解决方案是:

git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master

-1
投票

我有完全相同的问题:清理我的文件夹,重新安排和移动文件。我进入了:git rm。然后按Enter;然后觉得我的肠松弛了一点。幸运的是,我没有直接输入git commit -m“”。

但是,以下命令

git checkout -- .

恢复了一切,挽救了我的生命。


229
投票

我git-rm了几个文件,并在我下次提交之前继续进行更改,当时我意识到我需要一些这些文件。您可以根据需要简单地检查错过/删除的单个文件,而不是藏匿和重置:

git stash
git reset --hard HEAD
git stash pop

这使您的其他未提交的更改保持不变,无需解决方法。


46
投票

要重新获得某些单个文件或文件夹,可以使用以下内容

git checkout HEAD path/to/file path/to/another_file

这将首先重新创建git reset -- path/to/file git checkout -- path/to/file 的索引条目,并重新创建文件,就像它在上一次提交中一样,即path/to/file

提示:可以将提交哈希传递给两个命令,以便从较旧的提交中重新创建文件。有关详细信息,请参阅HEADgit reset --help


27
投票

更新:

由于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 命令。


24
投票

如果最终没有上述工作,您可以使用此处的建议检索数据:git add

http://www.spinics.net/lists/git/msg62499.html

9
投票

如果您已提交并推送更改,则可以执行此操作以恢复文件

git prune -n
git cat-file -p <blob #>

7
投票

已经有一些很好的答案,但我可能会建议一种使用不多的语法,它不仅效果很好,而且非常明确你想要的东西(因此不可怕或神秘)

// Replace 2 with the # of commits back before the file was deleted.
git checkout HEAD~2 path/to/file

7
投票

撤消git rm

git checkout <branch>@{"20 minutes ago"} <filename>

undo git rm -r

git rm file             # delete file & update index
git checkout HEAD file  # restore file & index from HEAD

undo git rm -rf

git rm -r dir          # delete tracked files in dir & update index
git checkout HEAD dir  # restore file & index from HEAD

git rm -r dir # delete tracked files & delete uncommitted changes not possible # `uncommitted changes` can not be restored. 包括Uncommitted changesnot staged changes


3
投票

获取列表提交

staged changes but not committed

例如,稳定提交有哈希:git log --oneline

45ff319c360cd7bd5442c0fbbe14202d20ccdf81
© www.soinside.com 2019 - 2024. All rights reserved.