Ignoring Unwanted Files and Secrets using .gitignore Rules
Ignoring Unwanted Files and Secrets using .gitignore Rules
Not all files inside your project directory belong in version control. Build outputs, temporary OS files, package dependencies, and sensitive credentials must never be committed. Git uses the .gitignore configuration file to ignore these files automatically.
1. What Files Should Be Ignored?
In a professional software project, the following categories must be ignored:
- 1Secrets & Credentials:
.env,secrets.json,.pemSSH keys, AWS credentials. (Committing these leads to critical security breaches!) - 2Dependencies:
node_modules/,venv/,vendor/,target/. (These can be regenerated via package managers likenpm installorpip install). - 3Build Artifacts & Compiled Code:
dist/,build/,.next/,*.pyc,*.exe,*.dll. - 4Operating System & Editor Files:
.DS_Store(macOS),Thumbs.db(Windows),.idea/,.vscode/settings.json. - 5Log Files & Temporary Dumps:
*.log,npm-debug.log*,*.tmp.
2. Anatomy of a .gitignore File
A .gitignore file is a plain text file placed at the root of your repository. Each line specifies a pattern:
Pattern Matching Rules Table:
| Pattern Syntax | Matches | Example |
|---|---|---|
filename.ext | Matches filename.ext in any directory | .env ignores all .env files |
/filename.ext | Matches only in the root directory where .gitignore lives | /TODO.txt ignores root TODO.txt only |
directory/ | Matches the directory and all contents recursively | build/ ignores build folder |
* | Matches zero or more arbitrary characters | *.pdf ignores all PDF files |
** | Matches directories across leading or nested paths | **/logs/*.txt |
! | Negation rule (do not ignore this file) | !release.log |
3. The Golden Trap: Untracking Already-Tracked Files
.gitignore will NOT stop Git from tracking it! .gitignore only applies to untracked files.How to Untrack an Already-Committed File:
To remove a file from Git's tracking without deleting the file from your local disk, use git rm --cached:
4. Global .gitignore for Developer-Specific Files
Operating system junk files like macOS .DS_Store or Windows Thumbs.db shouldn't clutter every team project's repo .gitignore. You can configure a personal global gitignore:
Practice Quiz
.gitignore file in a Git project?.env) NEVER be committed to Git?*.log match inside a .gitignore file?secrets.json to .gitignore, but it was already committed last week, what happens?Git Branching Mechanics: Pointers, HEAD, and git branch
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.