gitcachinggitignoregit-rm

Why git rm --cached not remove local ever tracked file but others


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:

  1. save current work. (Machine A)
git add .
git stash save "work position"
  1. 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"
  1. pull from another machine(or another directory)(Machine B)
git pull

show files now

ls
file_not_to_track  README.md
  1. 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
  1. 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.


Solution

  • 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 delete action.