Part III: Chapter 3.8

.gitignore

The Filter

The .gitignore file tells Git which files to completely skip over when scanning your working directory. But it has one crucial constraint that catches everyone out: it only works on untracked files.

Live Pattern Matching

Edit the .gitignore on the left and watch the files on the right respond instantly. Pay attention to tracked.log.

.gitignore

Try typing *.log or temp/

Working Directory

main.js
data.csv
README.md
app.log
debug.log
tracked.login index
banner.png
temp/

How Patterns Work

Git reads .gitignore line by line. Each line is a glob pattern matched against file paths relative to the repo root. The most common patterns are:

  • *.log — ignore any file ending in .log
  • temp/ — ignore an entire directory named temp
  • build/ — ignore any build directory at any depth
  • /dist — ignore only a top-level dist directory
  • !important.log — un-ignore a specific file that a prior rule caught

The Golden Rule

.gitignore is consulted only when Git scans for untracked files — files that have never been staged or committed. If a file is already in the Index, Git has no reason to consult .gitignore; it already knows about the file.

This is why adding *.log after you accidentally committed a log file does nothing. The fix is to remove the file from tracking first, then add the pattern.

The Fix for Already-Tracked Files

git rm --cached removes a file from the Index (tracking) without deleting it from your disk. After that, .gitignore takes over.

Terminal
$# The wrong way (does nothing if already tracked):
$echo "*.log" >> .gitignore
$git status
nothing to commit, working tree clean
# tracked.log is still being tracked!
$
$# The right way:
$git rm --cached app.log
rm 'app.log'
$git commit -m "Stop tracking app.log"
[main 3f4a5b] Stop tracking app.log
# Now .gitignore silences it for everyone.