Ignoring Files: .gitignore Patterns, Global and Local Ignores, and Untracking Files
Keep build output, logs, secrets and personal files out of Git: .gitignore pattern rules, negation and its folder trap, nested ignore files, private and global ignores, checking why a file is ignored, untracking committed files, ignoring changes to tracked files, filters and empty folders.
kvi5hnuCode Sprout team member11 min readOn this page
Most projects contain files that shouldn't be committed: build output, dependency folders, logs, editor settings, and above all secrets. Listing them in a .gitignore file tells Git to leave them alone: they don't appear as untracked in git status, git add . skips them, and git add refuses them unless forced.
An ignore rule affects untracked files only. A file that's already tracked stays tracked, whatever .gitignore says. That's the source of the most common confusion, and it's covered below.
A first .gitignore
.gitignore is a plain text file, usually at the top of the repository, committed like any other file so that everyone shares the rules. Each line is a pattern:
git init -q trail-guide
cd trail-guide
mkdir -p build src
echo "# Trail guide" > README.md
echo "console.log('map')" > src/map.js
echo "bundle" > build/app.js
echo "error at line 3" > debug.log
echo "API_KEY=abc123" > .env
echo "--- before .gitignore"
git status -s
cat > .gitignore <<'RULES'
# Build output and logs
build/
*.log
# Local secrets
.env
RULES
echo "--- after .gitignore"
git status -s
echo "--- git add refuses an ignored file"
git add debug.log
--- before .gitignore
?? .env
?? README.md
?? build/
?? debug.log
?? src/
--- after .gitignore
?? .gitignore
?? README.md
?? src/
--- git add refuses an ignored file
The following paths are ignored by one of your .gitignore files:
debug.log
hint: Use -f if you really want to add them.
hint: Disable this message with "git config set advice.addIgnoredFile false"
The ignored files vanished from git status, and .gitignore itself appeared as a new file to commit. git add debug.log explains why it refused, and how to override: git add -f adds an ignored file anyway, after which it's tracked and the rule no longer applies to it.
Pattern rules
The rules look like shell wildcards, with a few Git-specific twists:
| Pattern | Matches |
|---|---|
*.log | any file ending in .log, in any folder |
debug.log | a file or folder named debug.log, in any folder |
/notes.tmp | notes.tmp only in the folder containing the .gitignore, not in subfolders |
build/ | any folder named build, in any folder, and everything inside it. A file named build isn't matched |
docs/drafts | docs/drafts relative to the .gitignore's folder only: a slash at the start or in the middle anchors the pattern |
**/temp | temp in any folder: the same as temp alone |
logs/** | everything inside logs/ |
a/**/b | a/b, a/x/b, a/x/y/b and so on |
[bB]uild/ | build/ or Build/ (a character class) |
?.txt | one character followed by .txt, such as a.txt |
!logs/keep.log | negation: don't ignore this path, even if an earlier pattern ignored it |
# comment | a comment (only at the start of a line) |
\#notes | a file whose name starts with # (escaped). \!important similarly matches a name starting with ! |
Three rules are worth remembering:
- A slash anywhere except the end anchors the pattern to the
.gitignore's folder.docs/draftsmatchesdocs/draftsbut notsrc/docs/drafts. With no slash, or only a trailing one, the pattern matches at any depth. - A trailing slash means "folders only".
- The last matching pattern wins, so a later
!patterncan re-include something an earlier pattern excluded.
Comments must be on their own line. *.log # logs is a single pattern matching names that end in .log # logs, which is almost never what's meant. Trailing spaces are ignored unless escaped with a backslash.
git check-ignore -v shows which rule matches a path. It's the fastest way to debug a .gitignore:
git init -q trail-guide
cd trail-guide
mkdir -p build src/build docs/drafts logs data/raw
touch app.log src/app.log logs/errors.log logs/keep.log notes.tmp src/notes.tmp \
build/app.js src/build/app.js docs/drafts/idea.md src/docs.md data/raw/survey.csv data/raw/README.txt
cat > .gitignore <<'RULES'
*.log
!logs/keep.log
/notes.tmp
build/
docs/drafts
data/raw/*
!data/raw/README.txt
RULES
for path in app.log src/app.log logs/errors.log logs/keep.log notes.tmp src/notes.tmp \
build/app.js src/build/app.js docs/drafts/idea.md data/raw/survey.csv data/raw/README.txt; do
git check-ignore -q "$path" && echo "ignored $path" || echo "not ignored $path"
done
echo "--- which rule decides, for two paths"
git check-ignore -v src/build/app.js logs/keep.log
ignored app.log
ignored src/app.log
ignored logs/errors.log
not ignored logs/keep.log
ignored notes.tmp
not ignored src/notes.tmp
ignored build/app.js
ignored src/build/app.js
ignored docs/drafts/idea.md
ignored data/raw/survey.csv
not ignored data/raw/README.txt
--- which rule decides, for two paths
.gitignore:4:build/ src/build/app.js
.gitignore:2:!logs/keep.log logs/keep.log
/notes.tmp ignored the top-level file but not src/notes.tmp, while build/ matched at both depths. logs/keep.log and data/raw/README.txt are re-included by negations. With -v, check-ignore prints the deciding rule as file:line:pattern. For logs/keep.log it prints the ! rule, which means the file is not ignored: -v shows the last matching pattern, whichever way it decides. (-q prints nothing and sets only the exit status, which suits scripts.)
The negation trap: ignored folders
A negation can't re-include a file whose folder is ignored. Git doesn't even look inside an ignored folder, so it never sees the file:
git init -q trail-guide
cd trail-guide
mkdir data
touch data/survey.csv data/README.txt
echo "=== ignoring the folder: the negation has no effect"
printf 'data/\n!data/README.txt\n' > .gitignore
git status -s --untracked-files=all
echo "=== ignoring the folder's contents instead: the negation works"
printf 'data/*\n!data/README.txt\n' > .gitignore
git status -s --untracked-files=all
=== ignoring the folder: the negation has no effect
?? .gitignore
=== ignoring the folder's contents instead: the negation works
?? .gitignore
?? data/README.txt
data/* ignores everything inside data/ but not the folder itself, so Git still looks inside, and the later !data/README.txt takes effect. For files deeper down, every folder on the way must be re-included the same way: data/*, !data/raw/, data/raw/*, !data/raw/README.txt.
Several .gitignore files
You can put a .gitignore in any folder. Its patterns are relative to that folder and apply to it and its subfolders, so a rule in src/.gitignore reading output.log ignores src/output.log and src/a/output.log, but not examples/output.log. The same effect from the top-level file needs the anchored pattern src/**/output.log, or src/output.log for that one path.
When rules in different files conflict, the file closer to the path wins: src/.gitignore overrides the top-level .gitignore for paths under src/.
Ignores that aren't shared
A committed .gitignore is for rules that apply to everyone. Two other places hold personal rules:
.git/info/excludeuses the same syntax but lives inside.git, so it's never committed. It's for files only you create in one repository, such as a scratch notes file.- A global ignore file applies to every repository on your computer. Git reads the file named by
core.excludesFile, or~/.config/git/ignorewhen that setting isn't set. Put operating-system and editor files there, such as.DS_Store,Thumbs.db,*.swpand.idea/, rather than adding them to every project's.gitignore.
mkdir -p ~/.config/git
printf '.DS_Store\n*.swp\n' > ~/.config/git/ignore # global: every repository
git init -q trail-guide
cd trail-guide
echo "# Trail guide" > README.md
touch .DS_Store README.md.swp my-scratch.txt
echo "my-scratch.txt" >> .git/info/exclude # this repository only
git status -s
echo "--- why each file is ignored"
git check-ignore -v .DS_Store README.md.swp my-scratch.txt
?? README.md
--- why each file is ignored
/tmp/home/.config/git/ignore:1:.DS_Store .DS_Store
/tmp/home/.config/git/ignore:2:*.swp README.md.swp
.git/info/exclude:7:my-scratch.txt my-scratch.txt
Precedence runs from most to least specific: .gitignore files (deeper ones first), then .git/info/exclude, then the global file. So a project can re-include with ! something your global file ignores.
Don't rely on a global ignore file for files the project produces, such as build output or .env: teammates won't have your global file, and will commit them. Those rules belong in the project's .gitignore.
Seeing everything that's ignored
git init -q trail-guide
cd trail-guide
mkdir -p build/js
echo "# Trail guide" > README.md
touch debug.log build/js/app.js build/js/map.js
printf 'build/\n*.log\n' > .gitignore
git add . && git commit -q -m "Start project"
echo "=== git status --ignored"
git status --short --ignored
echo "=== every ignored file, one per line"
git status --short --ignored --untracked-files=all
echo "=== the same with ls-files"
git ls-files --others --ignored --exclude-standard
=== git status --ignored
!! build/
!! debug.log
=== every ignored file, one per line
!! build/js/app.js
!! build/js/map.js
!! debug.log
=== the same with ls-files
build/js/app.js
build/js/map.js
debug.log
git status --ignored lists ignored paths with !!, collapsing an ignored folder to one entry. --untracked-files=all lists every file inside. git ls-files --others --ignored --exclude-standard prints the same list without status codes, for scripts. To delete ignored files, use git clean -X (article 28).
Starting a .gitignore: templates
Most ecosystems have well-known ignore lists, and there's no need to write one from scratch:
- GitHub's gitignore repository (
github.com/github/gitignore) has templates for most languages, frameworks and editors, and GitHub, GitLab and Bitbucket offer them when you create a repository. gitignore.io, now hosted by Toptal, combines templates, such as Node plus macOS plus VS Code, into one file.- Framework generators such as
create-vite,cargo newanddotnet new gitignorewrite a suitable file for you.
Read a template before using it, and remove rules that don't apply, so the file stays understandable.
The file is already tracked: stop tracking it
Adding a pattern to .gitignore doesn't affect files Git already tracks. If you committed debug.log or .env earlier, Git keeps tracking changes to it. To stop, remove it from the staging area with git rm --cached, which keeps your copy on disk, and commit:
git init -q trail-guide
cd trail-guide
mkdir build
echo "# Trail guide" > README.md
echo "error" > debug.log
echo "bundle" > build/app.js
git add . && git commit -q -m "Start project" # oops: the log and build output were committed
printf 'build/\n*.log\n' > .gitignore
echo "more errors" >> debug.log
echo "--- .gitignore doesn't help: debug.log is tracked, so its change shows"
git status -s
git rm -r -q --cached . # empty the staging area (files stay on disk)
git add . # re-add everything, now honouring .gitignore
echo "--- staged: the ignored files are removed from tracking"
git status -s
git commit -q -m "Stop tracking build output and logs"
echo "--- still on disk"
ls build debug.log
--- .gitignore doesn't help: debug.log is tracked, so its change shows
M debug.log
?? .gitignore
--- staged: the ignored files are removed from tracking
A .gitignore
D build/app.js
D debug.log
--- still on disk
debug.log
build:
app.js
git rm -r --cached . followed by git add . re-adds every file through the current ignore rules: it's the quick way to untrack everything .gitignore now covers. For one file, git rm --cached debug.log is enough. Run it with no other uncommitted changes, so the resulting commit contains only the untracking.
Two cautions:
- When teammates pull this commit, Git deletes the untracked files from their working trees, because the commit removes them. Warn people before untracking a file they need locally, such as a config file, or ask them to copy it first.
- The files remain in earlier commits. A committed secret must be revoked, and removed from history with
git filter-repoif necessary (article 47).
Ignoring changes to a tracked file
Sometimes a file must stay tracked, such as a config file with defaults, but you need local changes that shouldn't be committed. Ignore rules can't help, because the file is tracked. Git has two index flags, set with git update-index, that are often suggested for this. They're different, and neither is a full solution:
| Flag | Meant for | Behaviour |
|---|---|---|
--assume-unchanged | performance: telling Git not to check huge files that you promise won't change | Git skips checking the file. If an incoming change touches it, Git may refuse or silently drop your edit: it's a promise, not a protection |
--skip-worktree | local edits to a file you don't want Git to touch | Git treats the file as unchanged and keeps your version. Operations that need to update it, such as a pull that changes it, stop with an error instead of overwriting it |
git init -q trail-guide
cd trail-guide
printf 'api_url=https://api.example.com\ndebug=false\n' > config.ini
git add . && git commit -q -m "Add default config"
sed -i 's/debug=false/debug=true/' config.ini
echo "--- the local edit shows up"
git status -s
git update-index --skip-worktree config.ini
echo "--- after --skip-worktree: hidden"
git status -s
echo "--- flagged files: S means skip-worktree"
git ls-files -v | grep '^S'
git update-index --no-skip-worktree config.ini
echo "--- flag removed: the edit is visible again"
git status -s
--- the local edit shows up
M config.ini
--- after --skip-worktree: hidden
--- flagged files: S means skip-worktree
S config.ini
--- flag removed: the edit is visible again
M config.ini
git ls-files -v marks skip-worktree files with S, and assume-unchanged files with a lower-case letter, such as h. Both flags are local: they're stored in your index and never shared or committed.
The better long-term fix is to not track the file at all: commit a template such as config.example.ini, ignore config.ini, and have each developer copy the template. Or make the application read local overrides from an ignored file.
Hiding part of a file: clean filters
A clean filter transforms a file's content as Git stages it, so you can keep lines out of commits while they stay in your working copy. For example, to never commit lines marked NOCOMMIT:
git init -q trail-guide
cd trail-guide
git config filter.nocommit.clean "grep -v NOCOMMIT"
echo "settings.js filter=nocommit" > .git/info/attributes
cat > settings.js <<'JS'
const port = 8080;
const debug = true; // NOCOMMIT
JS
git add settings.js && git commit -q -m "Add settings"
echo "--- committed version"
git show HEAD:settings.js
echo "--- working copy still has the line"
cat settings.js
--- committed version
const port = 8080;
--- working copy still has the line
const port = 8080;
const debug = true; // NOCOMMIT
The filter is defined in your config and applied through an attributes file, here .git/info/attributes so it stays private. Filters slow down operations on the affected files, and a checkout or merge that rewrites the file drops your local lines. Use them as a short-term convenience. Article 35 covers attributes and filters in more depth.
Empty folders
Git tracks files, so an empty folder can't be committed. To keep a folder in the repository, put a file in it. By convention it's called .gitkeep, an empty file with no special meaning to Git, or a short README that explains what the folder is for. For a folder whose contents should be ignored but which must exist, such as uploads/, combine it with a .gitignore inside the folder:
# uploads/.gitignore: ignore everything here except this file
*
!.gitignore
What's current
- Global ignores can live in
~/.config/git/ignorewithout any configuration.core.excludesFileis only needed for a different location. git status --ignoredhas modes: the default,traditional, also lists a folder when every file in it is ignored, while--ignored=matchinglists only paths that match an ignore pattern themselves, so an ignoredbuild/folder appears once. In the default mode, add--untracked-files=allto list every file inside ignored folders.- Hosting services offer
.gitignoretemplates when creating a repository, and many also scan pushes for secrets, as a safety net for files that should have been ignored.
Common questions
I added a file to .gitignore, but Git still shows changes to it. Why?
The file is tracked. Ignore rules only apply to untracked files. Run git rm --cached <file> and commit, and from then on the rule applies.
Should .gitignore itself be committed?
Yes, so everyone shares the project's rules. Personal rules go in .git/info/exclude or your global ignore file.
Should I commit lock files such as package-lock.json or Cargo.lock?
For applications, yes: they make installs reproducible. Libraries vary by ecosystem. Rust now recommends committing Cargo.lock for libraries too. Don't ignore them by default.
How do I ignore a file only in one folder, not everywhere?
Anchor the pattern, as in /debug.log for the top folder or src/debug.log for one subfolder, or put the rule in a .gitignore inside that folder.
My negation pattern doesn't work. Why?
Usually because a parent folder is ignored, so Git never looks inside it. Ignore the folder's contents with folder/* instead of folder/, then negate. git check-ignore -v <path> shows which rule wins.
Summary
.gitignorepatterns keep untracked files out ofgit statusandgit add. They don't affect tracked files.- A slash at the start or in the middle anchors a pattern, a trailing slash means folders only, and the last matching pattern wins.
!re-includes a path, but not inside an ignored folder: usefolder/*instead offolder/..git/info/excludeholds private rules for one repository, and~/.config/git/ignoreholds rules for all your repositories.git check-ignore -vexplains why a path is ignored, andgit status --ignoredlists ignored files.- To stop tracking a committed file, use
git rm --cachedand commit. Teammates' copies are deleted when they pull. --skip-worktreehides local edits to a tracked file, but a template file plus an ignored local copy is the cleaner design.
Practice questions
A .gitignore contains docs/*.pdf. Is guides/docs/manual.pdf ignored? Is docs/old/manual.pdf?
Answer
Neither. The slash in the middle anchors the pattern to the .gitignore's folder, so it only matches docs/<name>.pdf directly inside the top-level docs/. And * doesn't match /, so it doesn't reach into docs/old/. Use docs/**/*.pdf for all PDFs anywhere under the top-level docs/, or **/docs/*.pdf for docs/ folders at any depth.
You want to ignore everything in assets/ except assets/logo.svg. Why doesn't assets/ followed by !assets/logo.svg work, and what does?
Answer
assets/ ignores the folder itself, so Git never looks inside it and the negation can't apply. Use:
assets/*
!assets/logo.svg
assets/* ignores the folder's contents rather than the folder, and the negation then re-includes the logo.
A teammate committed node_modules/ months ago. You add node_modules/ to .gitignore. What else is needed, and what happens to everyone's local node_modules/ folder?
Answer
Run git rm -r --cached node_modules and commit, together with the .gitignore change. Your folder stays on disk. When teammates pull, Git deletes the tracked node_modules files from their working trees, because the commit removes them, so they reinstall dependencies with npm install. From then on, the folder is ignored.
Previous: Viewing Changes With git diff: Unstaged, Staged, Commits, Branches and Word Diffs
Next: Browsing History With git log: Formatting, Graphs, Filtering and Searching

More in Git Course
Quiz: Git Delicate Details
Twenty-five questions on Git's subtle corners: what commit -a and stash leave out, empty folders, ignore patterns and negation, HEAD~ versus HEAD^, ours and theirs in a rebase, tags that don't move or don't push, describe, merge reverts, diff exit codes, stash conflicts and more.
Quiz: Git Interview Questions
Thirty Git questions of the kind asked in developer interviews: Git versus GitHub, the staging area, merge versus rebase, fetch versus pull, reset, revert and restore, detached HEAD, conflicts, force pushing, stash, cherry-pick, reflog, bisect, submodules, LFS and how commits are identified.
Quiz: Git Course Final Exam (All Parts)
The final exam for the Git course: thirty questions across all twelve parts, from the three areas and staging through branching, remotes, undoing, history investigation, configuration, tags, larger projects, patches, rewriting, internals and troubleshooting.
Quiz: Professional Git Practice (Git Part 12)
Sixteen questions on migrating to Git from Subversion, TFVC and Mercurial, team best practices for commits, branches and reviews, repository hygiene, and diagnosing and fixing the most common Git errors, with explanations.
Discussion
Sign in to ask a question or share what you learned.