在git中取消删除已删除的文件

本文翻译自:Unstage a deleted file in git
Usually, to discard changes to a file you would do: 通常,要放弃对文件的更改,您将执行以下操作:

git checkout --

What if the change I want to discard is deleting the file? 如果我要丢弃的更改是删除文件怎么办? The above line would give an error: 以上行会出错:
error: pathspec '' did not match any file(s) known to git.

【在git中取消删除已删除的文件】 What command will restore that single file without undoing other changes? 什么命令将恢复该单个文件而不撤消其他更改?
bonus point: Also, what if the change I want to discard is adding a file? 奖励点:另外,如果我要丢弃的更改是添加文件怎么办? I would like to know how to unstage that change as well. 我想知道如何取消这种变化。
#1楼
参考:https://stackoom.com/question/eFA7/在git中取消删除已删除的文件
#2楼
If it has been staged and committed, then the following will reset the file: 如果已经暂存并提交,则以下内容将重置文件:
git reset COMMIT_HASH file_path git checkout COMMIT_HASH file_path git add file_path

This will work for a deletion that occurred several commits previous. 这将适用于之前发生过几次提交的删除。
#3楼
Both questions are answered in git status . 这两个问题都以git status回答。
To unstage adding a new file use git rm --cached filename.ext 要取消添加新文件,请使用git rm --cached filename.ext
# Changes to be committed: #(use "git rm --cached ..." to unstage) # #new file:test

To unstage deleting a file use git reset HEAD filename.ext 要取消暂停删除文件,请使用git reset HEAD filename.ext
# Changes to be committed: #(use "git reset HEAD ..." to unstage) # #deleted:test

In the other hand, git checkout -- never unstage, it just discards non-staged changes. 另一方面, git checkout --永远不会失败,它只会丢弃非分阶段的变化。
#4楼
The answers to your two questions are related. 你的两个问题的答案是相关的。 I'll start with the second: 我将从第二个开始:
Once you have staged a file (often with git add , though some other commands implicitly stage the changes as well, like git rm ) you can back out that change with git reset -- . 一旦你上传了一个文件(通常使用git add ,虽然其他一些命令也隐含地对这些更改进行了调整,比如git rm )你可以使用git reset -- 来取消该更改。
In your case you must have used git rm to remove the file, which is equivalent to simply removing it with rm and then staging that change. 在你的情况下,你必须使用git rm删除文件,这相当于简单地用rm删除它然后暂存该更改。 If you first unstage it with git reset -- you can then recover it with git checkout -- . 如果您首先使用git reset -- 取消它,则可以使用git checkout -- 恢复它。
#5楼
Assuming you're wanting to undo the effects of git rm or rm followed by git add -A or something similar: 假设你想要撤消git rm rm 然后是git add -A或类似的东西:
# this restores the file status in the index git reset -- # then check out a copy from the index git checkout --

To undo git add , the first line above suffices, assuming you haven't committed yet. 要撤消git add ,假设尚未提交,则上面的第一行就足够了。

    推荐阅读