Gitignore Wildcard and Glob Pattern Guide
Master gitignore wildcard syntax including *, **, ?, and character ranges. Learn the difference between directory and file matching with practical examples.
Detailed Explanation
Gitignore uses a pattern syntax similar to shell globbing but with important differences. Understanding wildcards is the key to writing precise, maintainable ignore rules that do not accidentally exclude or include the wrong files.
The * wildcard (single level):
* matches any characters except a slash (/). It only operates within a single directory level.
*.log— Matcheserror.log,debug.login the current directory and all subdirectories.build/*— Matches files directly insidebuild/but NOT files inbuild/sub/dir/.*.py[cod]— Combines with character classes to match.pyc,.pyo, and.pydfiles in one pattern.
The ** wildcard (cross-directory):
** matches zero or more directories. It is the most powerful glob pattern available:
**/logs— Matches alogsdirectory anywhere in the tree (logs/,src/logs/,a/b/c/logs/).logs/**— Matches everything inside thelogs/directory at any depth.**/logs/**— Matches everything inside anylogs/directory, located anywhere in the tree.a/**/b— Matchesa/b,a/x/b,a/x/y/b, and so on.
The ? wildcard:
? matches exactly one character (except /):
file?.txt— Matchesfile1.txt,fileA.txtbut NOTfile10.txt.
Character ranges [...]:
*.[oa]— Matches.oand.afiles (C object files and archives).temp[0-9].log— Matchestemp0.logthroughtemp9.log.[Dd]ebug/— Matches bothDebug/anddebug/for case flexibility.
Trailing slash (directory matching):
A trailing / means the pattern only matches directories:
build/— Ignores thebuilddirectory and everything inside it.build(no slash) — Ignores both a file namedbuildAND a directory namedbuild.
Leading slash (root-relative):
A leading / anchors the pattern to the repository root:
/build— Only ignoresbuildat the repository root, NOTsrc/build.build(no leading slash) — Ignoresbuildat any level in the directory tree.
Escaping special characters:
Use backslash to match literal special characters: \# matches a file starting with #, \! matches a file starting with !.
Performance tip: Specific patterns (e.g., /node_modules/) are faster than broad wildcards (e.g., **/node_modules/) because git can skip directory traversal. Use the leading slash when the ignored path is always at the repository root.
Use Case
A developer writing a .gitignore for a monorepo needs to understand how ** patterns work to ignore build directories in all 15 packages without listing each one individually.