Git and GitHub course menu
.gitignore Explained: How to Ignore Files in Git
Keep node_modules, build output, .env files and logs out of Git with .gitignore. Learn the patterns, negation, how to stop tracking a file already committed, and git check-ignore.
On this page
Not everything in a project folder belongs in Git. A .gitignore file lists the files Git should pretend are not there.
What should not be committed#
Lock files such as package-lock.json should be committed, because they record exact versions.
Create a .gitignore#
This project has some files we do not want to track:
mkdir node_modules logs
echo "x" > node_modules/lib.js
echo "x" > logs/today.log
echo "API_KEY=secret" > .env
git status --short?? .env
?? logs/
?? node_modules/Create .gitignore in the project root:
node_modules/
logs/
.envNow those files have gone from the list, and only .gitignore itself is left:
git status --short?? .gitignoreCommit .gitignore so that everyone on the team shares it:
git add .gitignore
git commit -q -m "Ignore dependencies, logs and env file"
git statusOn branch main
nothing to commit, working tree cleanPatterns#
An exception must come after the pattern it overrides:
printf '*.log\n!important.log\n' >> .gitignore
echo "a" > debug.log
echo "b" > important.log
git status --short M .gitignore
?? important.logA file is ignored and you want to know why#
git check-ignore -v debug.log.gitignore:4:*.log debug.logThis prints the rule and the line number that matched.
.gitignore does not affect tracked files#
Ignore rules apply only to untracked files. If you already committed a file, adding it to .gitignore changes nothing. Stop tracking it, while keeping your copy:
echo "*.tmp" >> .gitignore
git rm --cached cache.tmp
git add .gitignore
git commit -q -m "Stop tracking cache file"
git status --short
ls cache.tmprm 'cache.tmp'
cache.tmpThe file remains on disk, and Git no longer tracks it.
Starter templates#
GitHub offers a .gitignore template when you create a repository, and keeps a collection at github.com/github/gitignore for every common language. Use one of those rather than writing yours from scratch.
Common mistakes#
Practice#
Practice exercise
In a repository containing a.tmp and b.txt, ignore all .tmp files, then show the short status and the rule that ignores a.tmp.
Show solution
echo "*.tmp" > .gitignore
git status --short
git check-ignore -v a.tmp?? .gitignore
?? b.txt
.gitignore:1:*.tmp a.tmpKey takeaway#
Next: Undoing Changes.
Finished this lesson?