Ignoring Files
Use .gitignore to prevent Git from tracking files you don’t want committed, like dependencies, build output, or secrets.
Creating a .gitignore
Create a .gitignore file in your repository root:
# Dependencies
node_modules/
# Build output
dist/
build/
# Environment variables
.env
.env.local
# Logs
*.log
# OS files
.DS_Store
Thumbs.db
Git reads this file and skips anything that matches these patterns.
Pattern Syntax
node_modules/— ignores the directory*.log— ignores all.logfiles!important.log— negation: track this file even though*.logis ignored.env*— glob: matches.env,.env.local,.env.production
Directory vs File Patterns
Patterns ending with / match directories only. Without the trailing slash, Git matches both files and directories with that name.
logs/ # only matches directories named logs
logs # matches both files and directories named logs
Global Gitignore
Set a global ignore for files across all repos:
git config --global core.excludesfile ~/.gitignore_global
Useful for OS-specific files (.DS_Store, Thumbs.db) without polluting each project.
Removing Tracked Files
If you added a file to .gitignore after it was already tracked, you need to untrack it manually:
git rm --cached filename.txt
The file stays in your working directory but Git stops tracking it.
Best Practices
- Add
.gitignorebefore your first commit - Commit your
.gitignoreso the team shares it - Use a template for your tech stack (e.g., GitHub’s gitignore templates)
- Check what’s being tracked with
git statusregularly - Review
.gitignoreperiodically as projects evolve
Common Mistakes
- Forgetting that
.gitignoreonly prevents tracking new files — already tracked files must be untracked withgit rm --cached - Using absolute paths instead of relative patterns
- Putting sensitive files in
.gitignoreinstead of keeping them out of the repo entirely - Ignoring
.gitignoreitself (which is valid, but rare) - Not adding
.envearly and accidentally committing secrets