How does .gitignore work in Git?

A .gitignore file tells Git which files and folders to never track - useful for build outputs, secrets, and editor files.

GitVersion Control

Overview

A `.gitignore` file lists patterns for files and directories that Git should not track. Any matching path is excluded from `git add` and will not appear in `git status`. It does not affect files that are already being tracked - you must `git rm --cached` those first.

Key Points

  • •Patterns match relative to the `.gitignore` file location.
  • •Prefix `/` to anchor to the repo root: `/dist` ignores only the root `dist/` folder.
  • •Suffix `/` to match directories only: `node_modules/` ignores the folder but not a file named `node_modules`.
  • •Prefix `!` to un-ignore a pattern: `!src/important.log` re-tracks a file inside an ignored folder.
  • •A file already committed is NOT ignored by `.gitignore` - run `git rm --cached <file>` first.

Examples

Typical .gitignore for a Node.js project

text
# Dependencies
node_modules/

# Build output
dist/
.next/
out/

# Environment variables (secrets)
.env
.env.local
.env*.local

# Editor / OS
.vscode/
.DS_Store
Thumbs.db

# Logs
*.log
npm-debug.log*

Ignore a file that was already committed

bash
# Remove from Git tracking (keeps the file on disk)
git rm --cached .env

# Add pattern to .gitignore
echo ".env" >> .gitignore

git commit -m "stop tracking .env"

Without git rm --cached, adding to .gitignore has no effect on tracked files.

Check why a file is (or is not) being ignored

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

# See all ignored files in the project
git status --ignored

Global .gitignore for your machine

bash
git config --global core.excludesFile ~/.gitignore_global
# Add OS/editor patterns to ~/.gitignore_global so they apply to all repos

Pro Tip

Never commit secrets (API keys, `.env` files) even accidentally. Use a global `.gitignore` for editor files (`.DS_Store`, `.idea/`), and a per-project `.gitignore` for build artifacts and local config. Tools like `gitignore.io` generate templates for your stack.