问题
When untrack a file in the git repository, use git rm -r --cached .
. This will not remove the ever tracked file in local storage, but when other developers fetch this commit with git pull
, the ever tracked file will been removed on their machine storage.
You can reproduce it with:
- save current work. (Machine A)
git add .
git stash save "work position"
- create a new file and commit it.(Machine A)
echo hello>>file_not_to_track
git add .
git commit -m "add file file_not_to_track"
- pull from another machine(or another directory)(Machine B)
git pull
show files now
ls
file_not_to_track README.md
- untrack the file.(Machine A)
echo file_not_to_track >> .gitignore
git rm -r --cached .
git add .
git commit -m "untrack file_not_to_track"
git push
show files now
ls
file_not_to_track README.md
- fetch code(Machine 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
show files now
ls
README.md
As it shows git rm -r --cached .
remove ever tracked file on others repo but not in current repo.
回答1:
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.
回答2:
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.
回答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
来源:https://stackoverflow.com/questions/55663325/why-git-rm-cached-not-remove-local-ever-tracked-file-but-others