git rm --cached和git reset <file>有什么区别?

35
根据git rm文档
--cached
Use this option to unstage and remove paths only from the index.    
Working tree files, whether modified or not, will be left alone.

但根据这篇文章,取消暂存文件的操作使用以下命令:

git reset HEAD <file>

有什么不同吗?存在差异吗?


"git reset" 可以用于回到树的上一个版本,例如如果你想回到两个提交前的状态,可以执行 "git reset HEAD~2"。 - Jezor
5
如果HEAD中没有<file>,则两个命令等效。如果HEAD中有<file>,则git reset HEAD <file>将取消暂存该文件,而git rm --cached <file>将暂存该文件以便删除。 - user4003407
3个回答

42

git rm --cached命令可将文件标记为待删除状态,但不会从工作目录中删除该文件。因此,该文件将被视为未跟踪的文件。

进行试驾

git init test_repo
cd test_repo

touch test
git add test
git commit -m 'Added file test

git rm --cached test

git status
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        deleted:    test      <---- staged for removal

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        test              <-- still in the working dir

使用 git reset <file> 命令可以取消暂存文件。在上面的示例中,您可能希望使用 git reset test 命令来取消暂存删除操作。

git reset test
git status
On branch master
nothing to commit, working directory clean

20

使用带有标志 git rm --cached 的命令会将文件从索引中删除,但保留在工作目录中。这告诉 git 不再跟踪该文件。

另一方面,命令 git reset HEAD <file> 将文件保留为索引中的已跟踪文件,但索引中缓存的修改内容将丢失。这会导致缓存中的文件好像被 HEAD 中的文件覆盖了(同时工作树中的文件不变)。


2

清除缓存,请执行以下命令:

git rm -r --cached .


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接