Are multiple `.gitignore`s frowned on?
I can think of at least two situations where you would want to have multiple .gitignore
files in different (sub)directories.
Different directories have different types of file to ignore. For example the
.gitignore
in the top directory of your project ignores generated programs, whileDocumentation/.gitignore
ignores generated documentation.Ignore given files only in given (sub)directory (you can use
/sub/foo
in.gitignore
, though).
Please remember that patterns in .gitignore
file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name
applies to any file named name
in given directory and all its subdirectories, while /name
applies to file with this name only in given directory).
As a tangential note, one case where the ability to have multiple .gitignore
files is very useful is if you want an extra directory in your working copy that you never intend to commit. Just put a 1-byte .gitignore
(containing just a single asterisk) in that directory and it will never show up in git status
etc.
You can have multiple .gitignore
, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore
: git check-ignore -v -- afile
.
And you can have different version of a .gitignore
file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.
If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore
files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.
Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile
in order to see which gitignore run (from which .gitignore
file) is applied to 'yourfile
', and better understand why said file is ignored.
See "which gitignore
rule is ignoring my file?"