Advanced .gitignore Patterns
You've used basic .gitignore rules before. Now let's master the pattern syntax for precise control over which files Git tracks.
Pattern Syntax
Simple Patterns
*.log # ignore all .log files
debug.log # ignore a specific file
build/ # ignore the build directory
Directory vs File
A trailing slash means "directory only":
logs # ignores files AND directories named "logs"
logs/ # ignores only the directory named "logs"
Wildcards
* # matches everything except /
** # matches everything including /
? # matches any single character
[abc] # matches a, b, or c
[0-9] # matches any digit
The Double Star
The ** pattern is powerful for matching across directories:
**/logs # logs directory anywhere in the tree
**/logs/*.log # .log files inside any logs directory
src/**/*.test # .test files anywhere under src/
Negation Patterns
Use ! to un-ignore a file:
*.log # ignore all log files
!important.log # but keep this one
Order matters. Patterns are processed top-to-bottom. A later pattern overrides an earlier one.
build/ # ignore everything in build/
!build/.keep # this WON'T work — parent directory is ignored
To keep a file inside an ignored directory, you must un-ignore the directory first:
build/* # ignore contents of build (not the dir itself)
!build/.keep # now this works
Common Templates
Node.js / JavaScript
node_modules/
dist/
.env
.env.local
*.log
coverage/
Python
__pycache__/
*.pyc
.venv/
*.egg-info/
dist/
.env
Java / Kotlin
*.class
target/
build/
.gradle/
*.jar
General
# OS files
.DS_Store
Thumbs.db
# Editor files
.vscode/
.idea/
*.swp
*~
# Environment
.env
.env.local
Global .gitignore
You can set a global ignore file for patterns that apply to all your repos:
git config --global core.excludesFile ~/.gitignore_global
Put OS and editor patterns here so you don't repeat them in every project.
Checking Ignore Rules
Use git check-ignore to debug which rule is ignoring a file:
git check-ignore -v debug.log
# .gitignore:1:*.log debug.log
The -v flag shows which file and line number matched.
Already Tracked Files
Adding a file to .gitignore doesn't stop tracking it if it's already been committed. You must remove it from the index first:
git rm --cached secret.env # stop tracking but keep the file
git commit -m "Stop tracking secret.env"