Skip to content

gitignore: pattern not matching as expected

Quick summary

You added a pattern to .gitignore but files are still tracked — the pattern syntax or anchoring does not match the file paths.

Why this happens

  • The pattern is anchored differently than expected — a leading / anchors to the root, no leading / matches at any depth

  • The files were already tracked by git before the pattern was added — gitignore only affects untracked files

  • A trailing / is missing for directory-only patterns, or the wildcard does not match nested subdirectories

Minimal example

✗ Broken code
echo 'build' >> .gitignore
git add build/output.js  # file still added — already tracked
✓ Fixed code
git rm --cached -r build/  # untrack the directory
echo 'build/' >> .gitignore
git add build/output.js  # now ignored

Files already in the index are not affected by .gitignore — you must first remove them from tracking with git rm --cached, then the ignore pattern takes effect.

How to diagnose

  • Run git check-ignore -v <file> to see which gitignore pattern (if any) matches the file and from which file

  • Run git ls-files to check if the file is already tracked — tracked files are not affected by gitignore

  • Test the pattern with git check-ignore to verify it matches before committing the .gitignore change

How to fix

  • Remove already-tracked files from the index with git rm --cached <file> so gitignore can take effect

  • Adjust the pattern anchoring: use /build/ to ignore only the root-level build directory, or build/ to ignore any build directory

  • Use double-wildcard for recursive matching, e.g., /temp/ to ignore temp directories at any depth

How to prevent

  • Add .gitignore patterns before files are created or committed to avoid needing git rm --cached later

  • Test patterns with git check-ignore before committing .gitignore to confirm they match the intended paths

Related Resources

Related Glossary

Related Lessons

← Back to language