.gitignore
Introduction
Build output, dependencies, and secrets do not belong in Git history. A .gitignore file tells Git which paths to skip so git status stays clean and you never commit node_modules/ or .env by accident. This chapter covers rule syntax and templates for hello_code project types.
Prerequisites
Create .gitignore
At repository root:
my-app/
├── .git/
├── .gitignore
├── package.json
└── src/Example .gitignore:
Commit the ignore file like any source file:
git add .gitignore
git commit -m "Add gitignore for Node project"Code explanation:
- Rules apply to paths relative to
.gitignorelocation - Comments start with
#
Rule Syntax
| Pattern | Matches |
|---|---|
*.log | Any .log file in any subdirectory |
temp/ | Directory temp anywhere |
/temp/ | Only temp at repo root |
**/logs | logs in any directory |
!important.log | Negation—do not ignore this file |
\#literal | Escape # |
Code explanation:
- Trailing
/means directory - Leading
/anchors to repo root (in root.gitignore)
Patterns by Stack
Node / JavaScript / TypeScript
node_modules/
dist/
.next/
coverage/
*.tsbuildinfo
.npmSee JavaScript and TypeScript projects.
Java Maven
target/
*.class
*.jar
!.mvn/wrapper/maven-wrapper.jarSee Maven.
Java Gradle
.gradle/
build/
out/See Gradle.
Python
__pycache__/
*.py[cod]
.venv/
venv/IDE / editor
.idea/
*.iml
.vscode/*
!.vscode/settings.json
*.swpWarning
Never Ignore With Secrets Already Committed
.gitignore only prevents new tracks. If .env was committed, removing it from disk is not enough—you must untrack and rotate secrets.
Untrack a File Already in Git
git rm --cached .env
git commit -m "Stop tracking .env file"Code explanation:
--cachedremoves from Git index but keeps file on disk- Add
.envto.gitignorefirst or in same commit
Global Ignore (All Repos)
git config --global core.excludesFile ~/.gitignore_global~/.gitignore_global:
.DS_Store
Thumbs.db
*.swpPersonal OS/editor noise ignored everywhere.
Templates from GitHub
When creating a repo on GitHub, pick a .gitignore template (Node, Java, etc.). Or copy from github/gitignore.
Locally:
curl -o .gitignore https://raw.githubusercontent.com/github/gitignore/main/Node.gitignoreReview before commit—templates may include more than you need.
Verify Ignore Works
echo "SECRET=1" > .env
git status.env should not appear if listed in .gitignore.
Debug why a file is ignored:
git check-ignore -v .envShows which rule matched.
FAQ
Ignore file inside subdirectory?
Rules apply below that folder—root .gitignore is standard.
git add . still adds ignored files?
No—ignore wins unless force git add -f.
Ignore empty directories?
Git does not track empty dirs anyway—add .gitkeep if you need the folder in repo.
Share gitignore across monorepo?
One root .gitignore or nested files per package—both valid.
.env.example?
Commit example without secrets; ignore real .env.
Large build artifacts committed by mistake?
Remove from history with git filter-repo—advanced; prevent with ignore early.