How to Create a .gitignore File in Git
Create a
.gitignore file in your Git repository root by adding file patterns you want Git to ignore. Use a text editor to list files or folders, one per line, and save it as .gitignore.Syntax
The .gitignore file contains patterns that tell Git which files or folders to ignore. Each line is a pattern matching file names or directories.
*.logignores all files ending with.log.build/ignores the entirebuildfolder.!important.txtnegates ignore and tracksimportant.txt.
gitignore
*.log
build/
!important.txtExample
This example shows a .gitignore file that ignores log files, temporary files, and a build folder but tracks a specific config file.
gitignore
*.log
*.tmp
build/
!important.configOutput
If you run <code>git status</code>, files like <code>error.log</code>, <code>temp.tmp</code>, and anything inside <code>build/</code> will be ignored, but <code>important.config</code> will be tracked.
Common Pitfalls
Common mistakes include:
- Not placing the
.gitignorefile in the repository root. - Trying to ignore files already tracked by Git (you must untrack them first).
- Using incorrect patterns that don’t match the intended files.
To stop tracking a file already committed, use git rm --cached filename.
gitignore
Wrong pattern example: *.log/ Correct pattern: *.log
Quick Reference
Here is a quick guide to common .gitignore patterns:
| Pattern | Meaning |
|---|---|
| *.ext | Ignore all files with extension .ext |
| folder/ | Ignore entire folder named 'folder' |
| !file.txt | Do not ignore file.txt even if matched by other rules |
| # comment | Line starting with # is a comment |
| /file | Ignore file in the root directory only |
Key Takeaways
Create a .gitignore file in your repo root to list files Git should ignore.
Write one pattern per line to match files or folders to exclude.
Use ! to negate ignore rules for specific files.
Files already tracked must be untracked before .gitignore can ignore them.
Place .gitignore in the root for global effect in the repository.