Ignoring and Excluding Files
A .gitignore file lists patterns for files that Git should not track, such as build output, dependencies, local settings and secrets.
Where to ignore files
.gitignorein the repository: shared with the team. Use it for build output, dependencies and anything generated by the project’s own tools..git/info/exclude: personal and local to your clone, not shared.- A global ignore file (set with
git config --global core.excludesFile <path>): for things that belong to your own setup, such asThumbs.db,.DS_Storeor editor folders.
Pattern syntax
# Comments must be on their own line
node_modules/
*.log
/build
!important.log
.env
node_modules/ignores a directory at any depth.*.logignores every file ending in.log./buildignores only thebuildentry at the repository root.!important.logmakes an exception to an earlier rule.
Finding out why a file is ignored
git check-ignore -v <path> shows which rule matches. git status --ignored lists everything Git is currently ignoring.
Secrets
List files such as .env in .gitignore before you create them. Commit an example file (.env.example) with fake values so others know what to set. If a secret is ever pushed, change it immediately: removing it from the history is secondary, because it must be assumed to be exposed.
Try it
Find the .gitignore of a project you work on. For each rule, can you say what it hides? Then check git status --ignored to see what Git is currently ignoring.
Common mistakes
- Expecting .gitignore to untrack a file that is already committed. Run git rm --cached <file> and commit.
- Putting a comment after a pattern on the same line. It becomes part of the pattern.
- Creating .env before listing it in .gitignore.
Check yourself
- A file is in .gitignore but still shows as modified. Why?
- What is the difference between node_modules/ and /build?