Git Ignore and Patterns
The .gitignore file is one of the most important files in your repository for security and maintainability. It tells Git which files or directories to ignore and never track in version control.
🛡️ Why Use .gitignore?
- Security: Prevent sensitive information (API keys, passwords,
.envfiles) from leaking to GitHub. - Performance: Keep the repository size small by excluding large build artifacts (
node_modules/,dist/). - Cleanliness: Avoid cluttering the project with local OS files (
.DS_Store) or temporary logs.
1. Pattern Matching Syntax
Git uses a simple glob-style syntax to match files:
| Pattern | Match Description | Example |
|---|---|---|
*.log | Match all files ending in .log. | error.log, app.log |
temp/ | Match an entire directory and its contents. | temp/file.txt |
/root.txt | Match only if the file is in the root directory. | /root.txt (but not docs/root.txt) |
!keep.log | Negation: Do NOT ignore this file, even if it matches a pattern. | Overrides *.log. |
build/*.js | Match .js files only inside the build/ folder. | build/app.js |
2. Common Ignore Templates
Every language and OS has standard files that should be ignored. Here are the most common ones:
Node.js / Javascript
node_modules/
dist/
.env
npm-debug.logPython
__pycache__/
*.py[cod]
dev.env
venv/3. Maintaining Your Repository
Checking Ignored Files
If you're not sure why a file is being ignored, or want to see all ignored files:
git status --ignoredUntracking Already Committed Files
If you accidentally committed a file that should have been ignored, adding it to .gitignore won't remove it from Git's history. You must untrack it manually:
# Remove from Git index but keep the file on your computer
git rm --cached sensitive-config.json
# Now commit the change
git commit -m "Untrack sensitive config"[!IMPORTANT] The .gitignore file itself should ALWAYS be tracked. This ensures that everyone working on the project ignores the same files, maintaining consistency across the team.