.gitignore exclude specific file

user1995781 picture user1995781 · May 14, 2015 · Viewed 71.8k times · Source

I am trying to use .gitignore file to exclude templates.js located in public/app/ folder. My .gitignore file looks like this:

/vendor
/node_modules
composer.phar
composer.lock
.DS_Store
templates.js

But when I check in the Git Gui, the templates.js file is still show in it. How can I specifically exclude a file using .gitignore?

Answer

Willem Van Onsem picture Willem Van Onsem · May 14, 2015

In contrast to what the name "ignore" might suggest. .gitignore is only consulted when you git add files: in other words a file already added to the (index of the) repository will not be excluded based on the .gitignore.

First you better modify the .gitignore such that the file is no longer added. Add the following line to the .gitignore file:

public/app/template.js

Next you need to exclude the file from the repository. Probably you don't want to remove the file from your file system, this can be done with:

git rm --cached public/app/template.js

The --cached flag ensures the file will not be removed from your file system. (If not important, you can use git rm public/app/template.js, but this will remove the file).

Background

The reason .gitignore is not proactively used is because you sometimes might want to override the .gitignore. Say for instance you don't want to track *.log files, you can specify *.log in the .gitignore. But if there is a specific one you want to track you can add git add -f some.log. The -f flag forces git to add the file.