Git & Command Line Tutorial · Git Basics · Lesson 12 of 20

Ignoring Files with .gitignore

Keep build output, dependencies, logs and secrets out of your repository with .gitignore patterns, and stop tracking files that were committed by mistake.

Create a free account to save this page, take notes and track your progress. Sign in

.gitignore

A .gitignore file lists patterns Git should ignore:

node_modules/        # a folder anywhere
*.log                # all .log files
.env                 # secrets: never commit these
/build               # only the build folder at the root
!keep.log            # exception: do track this one

Commit .gitignore itself so the whole team shares it. Templates for every language live at github.com/github/gitignore.

Already committed by mistake?

Ignoring doesn't affect files Git already tracks. Remove them from the index (keeping the file on disk) with git rm --cached file, then commit. If you committed a secret, assume it's leaked: rotate the key, and only then clean the history.

.gitignore patterns and git rm --cached
git init -b main --quiet site && cd site
mkdir -p node_modules/lib build
touch index.html app.js .env debug.log keep.log node_modules/lib/x.js build/app.min.js

cat > .gitignore <<'EOF'
node_modules/
build/
*.log
!keep.log
.env
EOF
git status --short --untracked-files=all

git check-ignore -v debug.log .env       # which rule ignores a file

echo "API_KEY=secret" > settings.ini
git add settings.ini && git commit -m "Add settings (oops, has a key)" --quiet
echo "settings.ini" >> .gitignore
git rm --cached settings.ini --quiet     # stop tracking, keep the file
git add .gitignore && git commit -m "Stop tracking settings.ini" --quiet
echo "--- tracked files now:"
git ls-files

Output

?? .gitignore
?? app.js
?? index.html
?? keep.log
.gitignore:3:*.log	debug.log
.gitignore:5:.env	.env
--- tracked files now:
.gitignore

Run this on your computer — see “Get Started” for setup.

Test yourself

You committed config.local.json by mistake. How do you stop tracking it but keep the file?

  1. Delete the file
  2. Add it to .gitignore and run git rm --cached config.local.json
  3. git reset --hard
  4. Rename the file
Show answer

Answer: Add it to .gitignore and run git rm --cached config.local.json

Was this page helpful?