Advent Day 11: Removing (newly) ignored files

December 11, 2018

This is day 11 of my Git Tips and Tricks Advent Calendar. If you want to see the whole list of tips as they're published, see the index.

Yesterday I suggested that you set up a .gitignore to keep your repository tidy from temporary files, binaries and local configuration files.

But what if you've already added the files?

git status with an incorrectly ignored file

When you've already added and committed the files to the repository, you'll often see that these files have changed - even though you're trying to ignore them!

The problem is that the .gitignore file only applies to new ("untracked") files in the repository. Once you've added a file to your repository and committed it, the .gitignore no longer applies.

This is useful if you want to ignore a particular set of files by default but still add and commit one or two of them. (You can git add -f <file> to "force" an addition of a file that would otherwise be ignored.)

To get git to start ignoring the file properly, you can remove it from the repository:

git rm --cached .*.swp

The --cached flag indicates that git should remove the file from the index only (aka, the "cache"). This will leave the file on disk, and once you commit this change, the file will now be ignored as you expected.

git status with a properly ignored file