Ignoring Files: using gitignoreΒΆ

We have seen in the previous section that git recognises that files can be tracked or untracked. Sometimes we might have files in our working directory, such as compiled code, output files or editor backup files. We don’t want to track these files, but we also don’t want to see them every time we run git status.

Fortunately, git includes a way of ignoring particular files, or classes of files. Let’d create some files to ignore.

You may have noticed that the repository we have been working with has a source file, stats.py but we have not tested that it actually works. In order to do that we will need to provide a file containing the data to be processed. We will write a python script to generate these data.

First off, create a file. data.py with the following contents:

# Generate floating point values in the range 0.0 - 100.0 and
# write them to the file "data.txt" one value per line.

from random import random

f = open('data.txt', 'w')

for i in range(100):
    value = "%6.2f\n" % (100.0 * random())
    f.write(value)

f.close()

Next, execute this script from the command line to generate the data file, data.txt:

$ python data.py

You should now have three files in your directory:

$ ls
data.py data.txt stats.py

And you can now check that your stats.py code works:

$ python stats.py data.txt
100 values were read in
The sum of the input values is: 5091.91

Looks good. Now look at what git thinks about this:

$ git status
:
:
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    data.py
#    data.txt
no changes added to commit (use "git add" and/or "git commit -a")

We could leave things as they are, but being continually reminded that these files are untracked might be annoying if not confusing when we have a long list of untracked files. We may actually miss those files that we want tracked.

Here is what we can do to fix this. Create a file called .gitignore with the following content:

data.txt
data.py

Here is what git now thinks:

$  git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    .gitignore

Next, we should put .gitignore under version control. You know the drill: add the file, commit the change, check the status:

$ git add .gitignore

$ git commit -m"put .gitignore under version control"
[master c6f2746] put .gitignore under version control
 1 files changed, 2 insertions(+), 0 deletions(-)
 create mode 100644 .gitignore

$ git status
# On branch master
nothing to commit (working directory clean)

We could also put wildcards in the gitignore, to match types of file, for example *.o or *.pdf. We can also ignore entire directories, which might be useful if you use a build directory. Make sure to put each pattern on it’s own line, and check git help ignore for more details.