Ignoring files with .gitignore

Git · Essentials · 7 min

A clean repo has only source files; ignoring generated files avoids noise, conflicts and leaked secrets.

A `.gitignore` file lists patterns for files Git should treat as invisible: they won't show as untracked and git add . will skip them. Commit the .gitignore itself so the whole team shares it.

Pattern rules:

  • *.log matches any .log file in any directory.
  • build/ (trailing slash) matches only directories named build.
  • /config.local (leading slash) matches only at the level of this .gitignore.
  • **/tmp matches tmp at any depth; docs/**/*.pdf any PDF under docs.
  • !keep.log re-includes something an earlier pattern excluded. You cannot re-include a file if its parent directory is ignored.
  • Lines starting with # are comments.

.gitignore files can live in subdirectories and apply from there downward. For personal patterns that don't belong in the project (your editor's swap files, .DS_Store), use a global ignore file set by core.excludesFile, or .git/info/exclude for one repository.

The big gotcha: ignore rules only affect untracked files. If a file is already committed, adding it to .gitignore does nothing. Stop tracking it with git rm --cached <file> (which keeps it on disk) and commit that.

When a file is mysteriously ignored, git check-ignore -v <path> prints the exact file and line responsible. Templates for most languages live at github.com/github/gitignore.

Example

cat > .gitignore <<'END'
# dependencies and build output
node_modules/
dist/
*.log
# local secrets, but keep the example
.env*
!.env.example
END

git check-ignore -v dist/app.js
# .gitignore:3:dist/    dist/app.js

# Already committed .env by mistake? Stop tracking, keep the file
git rm --cached .env
git commit -m "Stop tracking .env"

Remember

  • Commit .gitignore so everyone ignores the same files
  • Ignore rules don't apply to files already tracked: use git rm --cached
  • git check-ignore -v explains why a path is ignored

Watch out for

  • Adding a committed secret to .gitignore and assuming it's gone — it's still in history and must be rotated.

Check yourself

  1. config.json is already committed. You add config.json to .gitignore and edit the file. What does git status show?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: git-scm.com/docs/gitignore