2

在 git 存储库中取消跟踪文件时,使用git rm -r --cached .. 这不会删除本地存储中曾经跟踪过的文件,但是当其他开发人员使用 获取此提交时git pull,曾经跟踪过的文件将在他们的机器存储中删除。

您可以通过以下方式重现它:

  1. 保存当前工作。(机器 A )
git add .
git stash save "work position"
  1. 创建一个新文件并提交它。(机器A
echo hello>>file_not_to_track
git add .
git commit -m "add file file_not_to_track"
  1. 从另一台机器(或另一个目录)拉取(机器 B
git pull

立即显示文件

ls
file_not_to_track  README.md
  1. 取消跟踪文件。(机器A
echo file_not_to_track >> .gitignore
git rm -r --cached .
git add .
git commit -m "untrack file_not_to_track"
git push

立即显示文件

ls
file_not_to_track  README.md
  1. 获取代码(机器 B
git pull
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From example.com:my/example_project
   6525df1..f413f8b  master     -> origin/master
Updating 6525df1..f413f8b
Fast-forward
 .gitignore        | 1 +
 file_not_to_track | 1 -
 2 files changed, 1 insertion(+), 1 deletion(-)
 create mode 100644 .gitignore
 delete mode 100644 file_not_to_track

立即显示文件

ls
README.md

正如它显示的那样,git rm -r --cached .删除其他仓库中曾经跟踪过的文件,但不在当前仓库中。

4

3 回答 3

3

git rm --cached tracks a change of removing the file from git, but does not remove the local copy. Running ls locally will still show the local file, but if you pull from another machine, the change of removing that file will be applied, and the file removed.

于 2019-04-13T08:06:25.767 回答
3

On Machine A:

git rm -r --cached .

Above command will remove files from the index (both README.md and file_not_to_track). At this time, the index is empty. However, file_not_to_track is still exists on file system.

--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 add .

With add action, git just added only README file. (file_not_to_track has been ignored).

On Machine B:

2 files changed, 1 insertion(+), 1 deletion(-)

With pull action, git recognizes that file_not_to_track is gone. Git perform an detele action.

于 2019-04-16T08:56:42.447 回答
3

This is how option --cached works, it removes the file from the git index. Working tree files will be left alone. However, Git will no more track this file in your local repository.

Look here for the --cached option:

https://git-scm.com/docs/git-rm

于 2019-04-16T09:07:25.343 回答