Ignoring Files with .gitignore
Not everything belongs in version control. Build artifacts, dependencies, secrets, and editor configurations should be excluded. The .gitignore file tells Git what to ignore.
Why Ignore Files?
Tracking the wrong files causes problems:
- Dependencies (
node_modules/,vendor/): Bloats repository size, slow clones - Build output (
dist/,*.o): Generated files that can be rebuilt - Secrets (
.env,*.pem): Security risk if pushed - Editor files (
.idea/,.vscode/): Personal preferences shouldn't be shared - OS files (
.DS_Store,Thumbs.db): System-specific clutter
Creating .gitignore
Create a .gitignore file in your repository root:
bash1$ cat <<'EOF' > .gitignore2# Dependencies3node_modules/4vendor/56# Build output7dist/8build/9*.o10*.pyc11__pycache__/1213# Environment & secrets14.env15.env.local16*.pem1718# Editor & OS files19.DS_Store20.idea/21.vscode/22*.swp23EOF
Pattern Syntax
Basic Patterns
| Pattern | Matches |
|---|---|
file.txt | file.txt in any directory |
/file.txt | file.txt only in root |
dir/ | Directory and all contents |
*.log | All .log files |
!important.log | Exception: track this file |
Wildcards
| Wildcard | Meaning |
|---|---|
* | Any characters except / |
** | Any directories |
? | Single character |
[abc] | One of a, b, or c |
Examples
gitignore1# All .log files anywhere2*.log34# All .log files in logs/ directory only5logs/*.log67# All files in any build directory8**/build/910# .env in root, but not in subdirectories11/.env1213# Ignore all .txt except readme.txt14*.txt15!readme.txt
Common Templates
Node.js
gitignore1node_modules/2npm-debug.log*3.env4dist/5coverage/
Python
gitignore1__pycache__/2*.py[cod]3.env4venv/5.pytest_cache/
Java
gitignore1*.class2*.jar3target/4.idea/5*.iml
General
gitignore1# OS2.DS_Store3Thumbs.db45# Editors6.idea/7.vscode/8*.swp9*~1011# Secrets12.env13.env.*14*.pem15*.key
Global Gitignore
For patterns that apply to all your repositories (like editor files), create a global gitignore:
bash1$ git config --global core.excludesFile ~/.gitignore_global2$ echo ".DS_Store" >> ~/.gitignore_global3$ echo ".idea/" >> ~/.gitignore_global
Already Tracked Files
.gitignore only affects untracked files. If a file is already tracked:
bash1# Remove from tracking but keep local file2$ git rm --cached secret.env3$ echo "secret.env" >> .gitignore4$ git commit -m "chore: stop tracking secret.env"
The --cached flag removes from Git but keeps the file on disk.
Checking What's Ignored
See which files are being ignored:
bash1$ git status --ignored
Check if a specific file would be ignored:
bash1$ git check-ignore -v debug.log2.gitignore:3:*.log debug.log
Template Resources
GitHub maintains language-specific templates:
Generate templates online:
Key Takeaway
A well-crafted .gitignore keeps your repository clean and secure. Ignore dependencies, build outputs, secrets, and editor configurations. Use global gitignore for personal preferences. Remember that .gitignore doesn't affect already-tracked files.