有时git会建议git rm——cached来取消文件,有时git会重置HEAD文件。什么时候用哪个?

D:\code\gt2>git init
Initialized empty Git repository in D:/code/gt2/.git/
D:\code\gt2>touch a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       a
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   a
#
D:\code\gt2>git commit -m a
[master (root-commit) c271e05] a
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a

D:\code\gt2>touch b

D:\code\gt2>git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       b
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add b

D:\code\gt2>git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   b
#

当前回答

>并不取消文件,它实际上是从repo中删除文件(假设它之前已经提交),但将文件留在你的工作树中(留下一个未跟踪的文件)。

git reset——<filePath>将取消对给定文件的任何阶段性更改。

也就是说,如果您使用缓存在一个新文件上的git rm—,它基本上看起来就像您刚刚取消了它的暂存,因为它之前从未提交过。

更新git 2.24 在这个新版本的git中,你可以使用git restore - staging而不是git reset。 参见git文档。

其他回答

在我看来,git rm——cached <file>从索引中删除了文件,而没有从目录中删除它,而普通的git rm <file>将两者都做,就像OS rm <file>将从目录中删除文件而没有删除它的版本。

我很惊讶没有人提到git reflog (http://git-scm.com/docs/git-reflog):

# git reflog
<find the place before your staged anything>
# git reset HEAD@{1}

reflog是一个git历史记录,它不仅跟踪对repo的更改,还跟踪用户的操作(例如。拉,签出到不同的分支等),并允许撤销这些操作。因此,与其取消被错误地暂存的文件,还不如恢复到没有暂存文件的位置。

这类似于git reset HEAD <file>,但在某些情况下可能更细粒度。

抱歉,我并没有真正回答你的问题,只是指出了另一种方法来取消我经常使用的文件(我非常喜欢Ryan Stewart和waldyrious的答案);)我希望这能有所帮助。

只使用:

git重置HEAD <文件名>

这将取消该文件并保留您对其所做的更改,因此您可以反过来更改分支,git会将这些文件添加到另一个分支。保留所有更改。

在> 2.2的新版本中,你可以使用git restore——staging <file_name>。 请注意这里 如果你想一次取消(移动到更改)你的文件,你可以使用上面的命令和你的文件名。如

git restore --staged abc.html

现在,如果您想一次性取消所有文件,您可以这样做

git restore --staged .

请注意空格和点(.)表示考虑将所有文件分段。

如果你无意中暂存了不想提交的文件,并且想要确保保留更改,你也可以使用:

git stash
git stash pop

这将执行HEAD重置并重新应用您的更改,允许您重新提交单个文件。如果你忘记了为pull请求创建一个特性分支(git stash;Git checkout -b <feature>;Git stash pop)。