Ignoring Files in Git

Have you ever tried to stage files from your Git repository and kept seeing things like system files? Well, I have. And I can’t take it anymore. I don’t want to have eleventy-billion .DS_Store files following me around for the rest of time. How do I ignore these? Well, Git has a handy way to do that.

Git has the ability to ignore any files, file patterns, or file extensions that you add to a .gitignore file. There are a couple of locations that this file can be depending on if you want Git to ignore files on a global scale or on a per repository basis.

If you want to ignore files on a global scale, then you can set the ‘core excludesfile’ option in your git config. To see what this option is currently set to just enter

git config --get core.excludesfile

As you can see, the location of my global excludes file is set to a hidden file in my home directory.

I’ve gone ahead and populated this file with a ignore template. Opening it up in a text editor, part of it looks like this:

Contents of my .gitignore file.

This file is just a long list of filenames and extensions that you want Git to ignore when watching files. If you would rather have this on a repository then you can create a .gitignore file and add it to your repo. This file will then overwrite your global ignore file.

There is one caveat to this ignore file. Git may not ignore files that are already being tracked (they’ve been staged and committed). I’ll use .DS_Store files as an example. If you have them in your ignore file (like I have in the screenshot above) then Git will ignore them. However, if you have added them to a repository before creating this file, then Git will not ignore them even if they are in the file.

How do you remove a file from being tracked once it is in a repository? With the following

git rm --cached <file_name>

Once this is done, the ‘git status’ command will show this.

Result of ‘git status’ after removing a file from being tracked.

At this point, you can ‘git commit’ and the file will no longer be tracked. That along with it being in the .gitignore file and it shouldn’t bother you again.