Git: Ignoring files

There are two main ways to ignore files in Git: locally by using .gitignore or globally using the core.excludesfile config variable.

Say we have a new git repository that contains a Java project (two ".java" files and their corresponding ".class" files). If run the git status command we would see all four files had were untracked and running git add . would add all four files to the staging area.

                    $ ls
                    algorithm.class   algorithm.java   program.class   program.java
                    $ git status
                    On branch master
                    
                    Initial commit
                    
                    Untracked files:
                    (use "git add ..." to include in what will be committed)
                    
                    algorithm.class
                    algorithm.java
                    program.class
                    program.java
                    
                    nothing added to commit but untracked files present (use "git add" to track)
                    $
                    

But we want to ignore the ".class" files from all of our commits. How do we do that? Well, one approach is to specifically name each file we want to commit:

                    $ git add algorithm.java
                    $ git add program.java
                    $
                    

But as we create more files this becomes a hassle. Instead we can create a ".gitignore" file and place it in the root of our git repository. In this file we list any files that we want git to ignore. Regexes come in very handy here - to ignore all ".class" files we can write *.class on the first line.

Now when we run git status the .class files have been ignored.

                    $ git status
                    On branch master
                    
                    Initial commit
                    
                    Untracked files:
                    (use "git add ..." to include in what will be committed)
                    
                    .gitignore
                    algorithm.java
                    program.java
                    
                    nothing added to commit but untracked files present (use "git add" to track)
                    $
                    

The second approach can be used to ignore files globally on your system. That means that they will be ignored for every repository you work with.

As above you will want a file containing regexes that git is to ignore - only this time they will be ignored for every repository on your machine. A useful place to store this file is in your home directory. You can create this file by using the command touch ~/.gitignoreglobal (or call it whatever you like). Then we just need to tell git where to look for this file by setting a variable in the config file.

                    $ git --global core.excludesfile ~/.gitignoreglobal
                    $