Tim
Tim

Reputation: 99536

How to specify to ignore a directory in .gitignore?

In a git repository, if I want to ignore a subdirectory (and therefore all the things under it) by adding it to .gitignore, is there any difference between

? They seem to work the same to me. Thanks.

Upvotes: 0

Views: 55

Answers (2)

torek
torek

Reputation: 489688

There are some differences but they are subtle.

Without a trailing slash

Using:

mysubdir

ignores any file or directory named mysubdir. If this is placed in the top level .gitignore, for instance, and you have directories A and B laid out as:

A/
    file
    mysubdir         <-- a file, not a directory!
B/
    file
    mysubdir/        <-- an actual directory
        file

then this .gitignore will ignore both A/mysubdir (a file) and B/mysubdir (a directory). By ignoring the second, it cuts off all files within B/mysubdir/ as well.

With a trailing slash

Using:

mysubdir/

ignores only directories named mysubdir. In this case, A/mysubdir is not ignored, because it's a file. But B/mysubdir is a directory, so it gets ignored.

With a trailing slash and an asterisk

Using:

mysubdir/*

tells Git that it should ignore all files and directories within mysubdir. For this to happen, mysubdir must be a directory (if it's not, it cannot contain files and more directories). So this seems, at first blush, the same as mysubdir/. But it's not!

When you use mysubdir/*, you force Git to read the directory itself, to list out all the files within it. It then checks each of these files against the patterns in the .gitignore file. This means you can add, to the .gitignore file, an override:

!mysubdir/precious

This file or directory is not ignored, due to the leading ! character. But for Git to find the file, Git must read the directory first. Had you listed mysubdir/ instead of mysubdir/*, Git would have not bothered to read the directory, and would not discover the existence of mysubdir/precious.

Of course, forcing Git to read the directory has a (slight) penalty: Git must spend whatever time it takes to read that directory. You should do this only if the penalty buys you something, such as not ignoring some file or subdirectory that is within that directory.

Upvotes: 1

Adrian
Adrian

Reputation: 46562

The "most correct" would be:

mysubdir/

The first in your list (mysubdir) will ignore directories and files by that name; likely not a problem, but potentially. The last only ignores the files under the directory, which has the same end result, because empty directories are ignored in Git by default.

If you look at the gitignore files provided by GitHub, you'll see they always ignore directories by the directory/ syntax.

Upvotes: 1

Related Questions