elefcode
← All guides

Dev Basics · 4 min read

.gitignore Explained: Patterns and Common Mistakes

A .gitignore file tells Git which files to leave out of version control: build output, dependencies, editor clutter, and — most importantly — secrets. Its pattern rules are short but have a few surprises.

Try it yourself with the related tool.

Generate a .gitignore →

Advertisement

Pattern rules

Each line is a pattern. *.log ignores every log file anywhere. A trailing slash such as build/ matches only directories. A leading slash such as /config.json anchors the pattern to the folder the .gitignore sits in. ** matches any number of directories, so logs/**/*.txt reaches into subfolders. Lines starting with # are comments.

Negation and its catch

A ! re-includes something an earlier pattern excluded: *.env followed by !example.env. The catch is that Git cannot re-include a file whose parent directory is ignored — if config/ is ignored, !config/keep.json does nothing. Ignore the directory's contents with config/* instead.

What to ignore

Ignore dependency folders (node_modules/, venv/), build output (dist/, .next/, target/), logs, OS files (.DS_Store, Thumbs.db), and secrets (.env). Personal editor settings are better placed in your global ignore file, configured with core.excludesFile, so every project does not need them.

Already committed? Ignoring is not enough

.gitignore only affects untracked files. If a file is already committed, run git rm --cached path to stop tracking it while keeping it on disk, then commit. If that file contained a secret, rotate the secret — it remains in the repository history.

Quick reference

Related guides