git rm -r --cached for fixing .gitignore file execution

Photo by Susan Q Yin on Unsplash

git rm -r --cached for fixing .gitignore file execution

Problem statement:

Sometimes you may encounter with situation when you add entries into .gitignore files and after commit made, file won't exclude these files from git repository. Most likely the problem is related to the fact that you may have already included files into index tracking by git add command. You can confirm this through the output of git status. If the file is not listed in the “Untracked files” section, then it is already tracked by Git and it will ignore the rule from the .gitignore file.

Solution method:

In order to actually ignore the file, you have to untrack it and remove it from the repository.

You can do that by using the following command:
git rm --cached file.txt or git rm -r --cached .

This command removes the file from the repository index without physically deleting the file (that's what --cached flag do). After committing that change, the file will be removed from the repository, and ignoring it should work properly. [Source]


git rm --> The git rm command can be used to remove individual files or a collection of files. The primary function of git rm is to remove tracked files from the Git index. Additionally, git rm can be used to remove files from both the staging index and the working directory. There is no option to remove a file from only the working directory. The files being operated on must be identical to the files in the current HEAD. If there is a discrepancy between the HEAD version of a file and the staging index or working tree version, Git will block the removal. This block is a safety mechanism to prevent removal of in-progress changes.

Note that git rm does not remove branches. [Source]

The -r option is shorthand for 'recursive'. When operating in recursive mode git rm will remove a target directory and all the contents of that directory.

The separator option -- is used to explicitly distinguish between a list of file names and the arguments being passed to git rm. This is useful if some of the file names have syntax that might be mistaken for other options.

--cached option specifies that the removal should happen only on the staging index. Working directory files will be left alone.


Executing git rm is not a permanent update. The command will update the staging index and the working directory. These changes will not be persisted until a new commit is created and the changes are added to the commit history. This means that the changes here can be "undone" using common Git commands.

git reset HEAD

A reset will revert the current staging index and working directory back to the HEAD commit. This will undo a git rm