Ignoring and Excluding Files

Expected level: Working

A .gitignore file lists patterns for files that Git should not track, such as build output, dependencies, local settings and secrets.

Where to ignore files

  • .gitignore in the repository: shared with the team. Use it for build output, dependencies and anything generated by the project’s own tools.
  • .git/info/exclude: personal and local to your clone, not shared.
  • A global ignore file (set with git config --global core.excludesFile <path>): for things that belong to your own setup, such as Thumbs.db, .DS_Store or editor folders.

Pattern syntax

# Comments must be on their own line
node_modules/
*.log
/build
!important.log
.env
  • node_modules/ ignores a directory at any depth.
  • *.log ignores every file ending in .log.
  • /build ignores only the build entry at the repository root.
  • !important.log makes an exception to an earlier rule.

Finding out why a file is ignored

git check-ignore -v <path> shows which rule matches. git status --ignored lists everything Git is currently ignoring.

Secrets

List files such as .env in .gitignore before you create them. Commit an example file (.env.example) with fake values so others know what to set. If a secret is ever pushed, change it immediately: removing it from the history is secondary, because it must be assumed to be exposed.

Try it

Find the .gitignore of a project you work on. For each rule, can you say what it hides? Then check git status --ignored to see what Git is currently ignoring.

Common mistakes

  • Expecting .gitignore to untrack a file that is already committed. Run git rm --cached <file> and commit.
  • Putting a comment after a pattern on the same line. It becomes part of the pattern.
  • Creating .env before listing it in .gitignore.

Check yourself

  • A file is in .gitignore but still shows as modified. Why?
  • What is the difference between node_modules/ and /build?

Related topics

Terms

Further reading