What is .gitignore?
The .gitignore file tells Git which files and folders it should ignore (not track).
This helps keep your repository clean by excluding:
- Log files
- Temporary files
- Build artifacts
- OS/editor-specific files (like .DS_Store, Thumbs.db)
- Personal or sensitive files
The .gitignore file itself is tracked by Git so everyone working on the project ignores the same files.
Why Use .gitignore?
- To keep local, temporary, or sensitive files out of version control
- To avoid cluttering your repository history with unnecessary files
- To ensure that build tools or editors don’t add extra files to your commits
- To share clean projects with collaborators
Create a .gitignore File
- Go to the root of your Git repository.
- Create the file:
touch .gitignore
- Add your ignore patterns.
Ignore Folders
To ignore an entire folder and its contents, add a trailing slash:
This will ignore any folder named temp anywhere in your project.
Wildcards & Patterns
Wildcards let you define flexible ignore rules:
*- Any number of characters
?- A single character
[abc]- Any character a, b, or c
[!abc]- Any character except a, b, or c
Examples:
*.tmp # All .tmp files
my?ile.txt # my1ile.txt, myAile.txt, etc.
log[0-9].txt # log1.txt, log2.txt, ... log9.txt
Negation (!)
To override ignore rules, use !:
*.log # Ignore all .log files
!important.log # But don't ignore important.log
Comments and Blank Lines
Lines starting with # are comments. Blank lines are ignored too.
# Ignore log files
*.log
# Ignore temp folders
temp/
Local & Personal Ignore Rules
If you want to ignore files only for yourself, add them to:
.git/info/exclude
Works the same as .gitignore, but isn’t shared with others.
Global .gitignore (User Level)
Ignore patterns across all your projects by creating a global ignore file:
git config --global core.excludesfile ~/.gitignore_global
Then add patterns (e.g., .DS_Store, Thumbs.db) to ~/.gitignore_global.
Stop Tracking a File Already Committed
Adding a file to .gitignore doesn’t remove it from the repository if it’s already tracked.
To stop tracking it:
git rm --cached filename.txt
This removes it from Git history but keeps it on your local machine. Future commits will ignore it.
Tips & Troubleshooting
- Check for typos – .gitignore is case-sensitive!
- Use git status to verify which files are tracked or ignored.
- Add comments to explain tricky ignore rules.
- Remember: .gitignore only affects new, untracked files — tracked files need to be removed with git rm --cached.