Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readGit
#Git#Gitignore#Configuration#CLI
3D illustration of file cards passing a filter gate while ignored cards fall into a bin

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

bash
# 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
bash
# 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 once

git 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

PatternMatchesDoes not match
buildAny file or directory named build, at any depthbuild/x is implied ignored via the directory
build/Directories named build onlyA file named build
/buildOnly at the repository rootsrc/build
*.logEvery .log at every depthlog.txt
**/*.logSame as *.log—
doc/*.md.md directly inside docdoc/sub/a.md
!keep.logRe-includes keep.logA file inside an excluded directory
[abc].txta.txt, b.txt, c.txtd.txt
SourceCommittedScopePrecedence
.gitignore in treeYesIts directory and belowHighest of the file sources, deeper beats shallower
.git/info/excludeNoWhole repository, one userLower than .gitignore
core.excludesFileNoEvery repository, one userLower still
git add -f / pathspecNoOne commandOverrides everything

Practical Edge Cases and Deep Dives

1. The negation that cannot work

gitignore
dist/ !dist/keep.txt # never re-includes anything
gitignore
dist/* !dist/keep.txt # works: keep.txt is re-included

Git'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

bash
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

bash
# 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

bash
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.php

Both 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

bash
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 tabs

On 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

gitignore
# Ignore everything except the source tree and CI config /* !/.gitignore !/src/ !/package.json !/tsconfig.json

The 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

SymptomCauseFix
Rule added, file still trackedIgnore does not affect tracked filesgit rm --cached <path>
!file has no effectParent directory is excludedExclude contents (dir/*), not the directory
node_modules shows in git statusRule missing or misspelled in a nested filegit check-ignore -v node_modules/x
Pattern ignored on one machine onlyGlobal or info/exclude rule, or case sensitivityCheck --show-origin, compare filesystems
.env committed anywayRule below a re-inclusion, or file staged before the rulegit ls-files -ci --exclude-standard, then rm --cached
Root-anchored rule matches too much or too littleMissing or extra leading /Anchor with /name, not name
Directory re-include failsdist/ then !dist/filedist/* then !dist/file
Ignored files still shipped in a Docker build.dockerignore is a separate fileAdd 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 lineEscape with \#

Try matching browser tools

All tools

Small utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Git guides

More in Git

All Git guides

The guides filed next to this one in Git, in library order.