Annex .gitignore syntax

Last updated: January 4, 2023

While writing your .gitignore file, you can add files to be excluded one by one. In many cases however, it is really convenient to use globing patterns to exclude many files at once. This annex presents the rules to write such patterns.

.gitignore rules

  • Each line in a .gitignore file specifies a pattern

  • Blank lines are ignored and can serve as separators for readability

  • Lines starting with # are comments

  • To add patterns starting with a special character (e.g. # , ! ), that character needs escaping with \

  • Trailing spaces are ignored unless they are escaped with \

  • ! negates patterns (matching files excluded by previous patterns become included again)

However it is not possible to re-include a file if one of its parent directories is excluded (Git doesn’t list excluded directories for performance reasons).

One way to go around that is to force the inclusion of a file which is in an ignored directory with the option -f .

Example: git add -f <file>

  • Patterns ending with / match directories. Otherwise patterns match both files and directories

  • / at the beginning or within a search pattern indicates that the pattern is relative to the directory level of the .gitignore file. Otherwise the pattern matches anywhere below the .gitignore level

Examples:
    - foo/bar/ matches the directory foo/bar , but not the directory a/foo/bar
    - bar/ matches both the directories foo/bar and a/foo/bar

  • * matches anything except /

  • ? matches any one character except /

  • The range notation (e.g. [a-zA-Z] ) can be used to match one of the characters in a range

  • A leading **/ matches all directories

Example: **/foo matches file or directory foo anywhere. This is the same as foo

  • A trailing /** matches everything inside what it precedes

Example: abc/** matches all files (recursively) inside directory abc

  • /**/ matches zero or more directories

Example: a/**/b matches a/b , a/x/b , and a/x/y/b

Comments & questions