Git ignore: Patterns, Negation, and Untracking Cached Files
Patterns are relative and last match wins, but a negation cannot revive a file inside an excluded directory. Ignore rules never touch tracked files: rm --cached first.

Quick Summary
.gitignore holds patterns matched against paths relative to the directory that contains the file. Patterns are read in order, and the last matching pattern wins, which is what makes negation (!) work — and also why a negation inside an excluded directory does nothing.
Git consults four sources: .gitignore files throughout the tree (deeper wins), .git/info/exclude for local-only rules, core.excludesFile (usually ~/.config/git/ignore) for global rules, and command-line excludes. Nothing there affects files that are already tracked: ignore rules only decide what git add will pick up from untracked paths.
The recurring bug is the parent-directory rule. Git does not descend into an excluded directory, so dist/ followed by !dist/keep.txt never re-includes the file. The fix is to exclude the contents, not the directory: dist/* and !dist/keep.txt.
Basic Syntax and Core Signatures
# Patterns, in the syntax that actually applies
build/ # directory named build, at any depth
/build/ # only the top-level build directory
*.log # any file ending in .log, at any depth
**/logs/*.txt # logs directory at any depth, .txt files only
!important.log # negate: re-include (only if the parent is not excluded)
doc/*.md # direct children only
?cache # single character wildcard
\#notes.md # a literal leading #
\!literal.txt # a literal leading !
name with space\ # trailing spaces are ignored unless escaped# Local and global sources
git config --global core.excludesFile ~/.config/git/ignore
printf '.DS_Store\nnode_modules/\n' >> ~/.config/git/ignore
echo '.env.local' >> .git/info/exclude # local only, never committed
# Debugging and repair
git check-ignore -v path/to/file # which pattern, from which file, which line
git status --ignored # show ignored files too
git ls-files -ci --exclude-standard # tracked files that the rules now ignore
git rm --cached -r . && git add . # re-apply ignore rules to the index
git add -f path/to/file # override a rule oncegit check-ignore -v is the answer to almost every "why is this ignored" or "why is this not ignored" question, because it prints the deciding rule rather than the list of candidates.
Key Comparison Table
| Pattern | Matches | Does not match |
|---|---|---|
build | Any file or directory named build, at any depth | build/x is implied ignored via the directory |
build/ | Directories named build only | A file named build |
/build | Only at the repository root | src/build |
*.log | Every .log at every depth | log.txt |
**/*.log | Same as *.log | — |
doc/*.md | .md directly inside doc | doc/sub/a.md |
!keep.log | Re-includes keep.log | A file inside an excluded directory |
[abc].txt | a.txt, b.txt, c.txt | d.txt |
| Source | Committed | Scope | Precedence |
|---|---|---|---|
.gitignore in tree | Yes | Its directory and below | Highest of the file sources, deeper beats shallower |
.git/info/exclude | No | Whole repository, one user | Lower than .gitignore |
core.excludesFile | No | Every repository, one user | Lower still |
git add -f / pathspec | No | One command | Overrides everything |
Practical Edge Cases and Deep Dives
1. The negation that cannot work
dist/
!dist/keep.txt # never re-includes anythingdist/*
!dist/keep.txt # works: keep.txt is re-includedGit's rule is explicit: it is not possible to re-include a file when a parent directory of that file is excluded, because Git never looks inside an excluded directory. The same trap appears with a wildcard that swallows the directory: **/node_modules excludes the directory, **/node_modules/* excludes its contents and is re-includable.
2. Ignoring something that is already committed
git rm --cached .env # untrack, keep the working file
git commit -m "chore: stop tracking .env"An added ignore rule changes nothing for a tracked file: git status stays clean and git add -A keeps updating it. git ls-files -ci --exclude-standard lists every tracked file the rules now ignore, which is a fast audit for leaked secrets and build output. For a file you must keep in the repository but want Git to stop noticing changes, git update-index --skip-worktree is better than --assume-unchanged: skip-worktree is honoured across pulls, while assume-unchanged is a promise Git is free to break when it needs to write the file.
3. Global rules, local rules, and a repository you cannot change
# Machine-wide, never shared
git config --global core.excludesFile ~/.config/git/ignore
# Repository-local, not committed
echo '*.local.json' >> .git/info/exclude
# Per-directory, committed: a nested .gitignore for a generated subtree
echo 'generated/' > src/proto/.gitignore~/.config/git/ignore is the right home for .DS_Store, editor swap files, and OS metadata; committing those to a shared repository is noise for everyone else. .git/info/exclude is for rules specific to your clone — a local dump file, a debug config. A nested .gitignore is how a generated directory inside the source tree documents its own rule instead of one line in the root file.
4. --assume-unchanged, --skip-worktree, and cache invalidation
git update-index --assume-unchanged config/local.php
git update-index --skip-worktree config/local.php
git ls-files -v | grep '^[a-z]' # lowercase = flagged
git update-index --no-skip-worktree config/local.phpBoth flags live in the index and are lost on a fresh clone, so neither is a substitute for an ignore rule. --assume-unchanged is an optimisation hint that Git may discard on merge; --skip-worktree is a promise that the file is not modified locally, and a pull that changes the file will produce a conflict rather than silently overwrite it. If you need a file that exists in the repository and is edited locally, a committed template plus an ignored real file (.env.example + .env) is the structure that survives everything.
5. Case, spaces, and line endings
git check-ignore -v Build/Output # core.ignoreCase on macOS/Windows
git config core.ignoreCase false # only on case-sensitive filesystems
printf 'a\tb\n' > 'file with tab.txt' # patterns need escaping for tabsOn a case-insensitive filesystem, build/ matches Build/, and the same .gitignore behaves differently for a Linux contributor. Trailing spaces in a pattern are stripped unless escaped, so a rule for name with space silently becomes name with space. CRLF is the third difference: a .gitignore committed with CRLF line endings works, but a rule ending in \r never matches — save it with LF like every other text file in the repository.
6. Whitelisting a directory with an exception
# Ignore everything except the source tree and CI config
/*
!/.gitignore
!/src/
!/package.json
!/tsconfig.jsonThe leading /* excludes each top-level entry rather than the root itself, which keeps the root traversable, so !/src/ can re-include the directory. Add !/src/** only if a nested rule inside src would otherwise exclude content — order matters, and git check-ignore -v src/lib/index.ts tells you which line decided.
Common Git Operation Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Rule added, file still tracked | Ignore does not affect tracked files | git rm --cached <path> |
!file has no effect | Parent directory is excluded | Exclude contents (dir/*), not the directory |
node_modules shows in git status | Rule missing or misspelled in a nested file | git check-ignore -v node_modules/x |
| Pattern ignored on one machine only | Global or info/exclude rule, or case sensitivity | Check --show-origin, compare filesystems |
.env committed anyway | Rule below a re-inclusion, or file staged before the rule | git ls-files -ci --exclude-standard, then rm --cached |
| Root-anchored rule matches too much or too little | Missing or extra leading / | Anchor with /name, not name |
| Directory re-include fails | dist/ then !dist/file | dist/* then !dist/file |
| Ignored files still shipped in a Docker build | .dockerignore is a separate file | Add the patterns there too |
Blank line at the end of a rule set breaks nothing, but a # mid-pattern does | # starts a comment only at the start of a line | Escape with \# |
Try matching browser tools
All toolsSmall utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Git guides
All Git guidesGit config: Aliases, rerere, and Credential Helpers
Five config scopes decide one value at a time. Aliases are user-level shorthand, rerere records conflict resolutions, and credential helpers choose where your secret lives.
Git Hooks: pre-commit, commit-msg, and Husky Automation
Hooks live in .git/hooks, which a clone never receives, so core.hooksPath and Husky are how they travel. Exit codes abort the operation, and every hook is bypassable.
Git bisect: Binary Search, Automated Scripts, and Bug Hunting
Mark one bad and one good commit and Git halves the range each step. bisect run automates it through exit codes, and monotonicity is the assumption that must hold.
Git worktree: Multiple Checked-Out Branches in One Repository
A linked worktree has its own HEAD, index, and files while sharing objects and refs. One branch per worktree, prune for deleted directories, and submodules that stay empty.
More in Git
All Git guidesThe guides filed next to this one in Git, in library order.