Git & GitHub ยท Chapter 11 of 42

.gitignore

A `.gitignore` file tells Git which files or folders to ignore, so they are never staged, committed, or shown as untracked. This is useful for build artifacts, dependency folders, and secrets.

You create a `.gitignore` file in your project root and list patterns for files you want Git to skip, such as `node_modules/` or `*.log`.

Syntax
# .gitignore example
node_modules/
*.log
.env

Common patterns

Use exact filenames like `secret.env`, wildcards like `*.log`, or folder patterns like `node_modules/` to ignore entire directories such as dependencies or build output.

Ignoring already-tracked files

Adding a file to .gitignore does not untrack it if it's already committed. Use `git rm --cached filename` to stop tracking it while keeping the local copy.

Example 1 (bash)
echo "node_modules/" >> .gitignore
echo "*.log" >> .gitignore
git status
Output
On branch main
nothing to commit, working tree clean

Adds ignore patterns so node_modules and log files no longer appear as untracked.

Example 2 (bash)
git rm --cached config.env
echo "config.env" >> .gitignore
Output
rm 'config.env'

Stops tracking a previously committed file and adds it to .gitignore so it stays ignored going forward.

Key points

  • .gitignore lists files and folders Git should never track.
  • Common entries include dependency folders and log files.
  • Already-tracked files need git rm --cached to stop being tracked.
  • Keeping secrets out of Git history is an important security practice.
๐Ÿ’ก Note: Never commit sensitive information like passwords or API keys โ€” use .gitignore and environment variables instead.

๐Ÿ“ Quick Quiz

1. What does a .gitignore file do?

2. What command stops tracking an already-committed file?

3. Which is a good candidate for .gitignore?