.gitignore exclude specific file

Solution 1:

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.

Solution 2:

Once a file has been 'added' to the git repository once, it will continue to be tracked regardless of whether or not it is listed in the .gitignore file.

I'm guessing you added the template.js file previously, in which case it will continue to have changes tracked, until you remove it from the repository. Once the file has been removed from the repository, it will be properly ignored via the .gitignore file.

The way to remove a file from a git repository (command-line) without deleting it is

git rm --cached FILENAME

Then once you do that and try to commit with the file in your gitignore, it won't do it.

Note that if you specifically add a file that you have in your gitignore, your manual adding of the file will override the gitignore.

Solution 3:

If you are already tracking a file (git add on it and git commit), .gitignore will not help.

I believe what you want is to stop tracking a file, and then use .gitignore to exclude it. To stop tracking a file but keep the file, use:

git rm --cached <file>

Solution 4:

In this case you can stop tracking templates.js with

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

As others have explained, .gitignore only ignores content to be added. For example, if you frequently use git add . and have templates.js in your .gitignore, then git will not add it.