Ignore generated files with .gitignore
Ignore generated files with .gitignore
Projects often generate files that should not become source history: build directories, local caches, editor files and environment-specific output.
What you’ll learn
- Write basic ignore patterns.
- Explain tracked versus ignored.
- Avoid committing common generated or secret files.
Decide what belongs in history
Source
Files needed to reproduce and review the project.
trackGenerated/local
Build outputs, caches and machine-specific files.
usually ignoreSecret
Credentials and private keys.
never commit
.gitignore mainly controls untracked paths
A .gitignore file contains patterns for paths Git should normally leave untracked. It does not retroactively remove a file that is already tracked.
If a tracked file should remain on disk but leave the repository, remove it from the index with git rm --cached, then commit that change. For project-wide ignore rules, commit the .gitignore file itself.
Add repository ignore rules
Run this in a disposable practice repository unless the lesson explicitly says otherwise.
printf "node_modules/\n.env\n*.log\n" > .gitignore
git add .gitignore
git commit -m "Add project ignore rules"
git statusThe rules ignore a dependency directory, a local environment file and log files when those paths are untracked. Keep secrets out of Git history entirely; ignoring a file only after a secret was committed does not erase that earlier history.
Practice: .gitignore and tracked files
Your task: Create debug.log before and after adding *.log to .gitignore. Use git status to confirm it stays untracked. Then ask why a previously committed debug.log would behave differently.
Common pitfall to avoid
Never rely on .gitignore as a secret-management system. If a credential has been committed, rotate/revoke it and follow an appropriate history-removal process if necessary.
Check your understanding
.gitignore and tracked files: what to remember
Ignore generated files with .gitignore is complete when you can explain the state being changed before you run the command, not merely repeat the syntax.
Read further: official supporting documentation.
Reaching the recap and completing the quizzes are separate milestones.