Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 78 ยท The Basic Workflow

.gitignore and Untracked Files

Learn .gitignore patterns, negation and directory rules, global ignore files, git check-ignore, how to stop tracking a file, and how git clean removes untracked files safely.

Not every file in your project folder belongs in version control. Compiled output, downloaded dependencies, log files, editor settings, local configuration and secrets are all things you do not want in history. They are large, they change on every build, they differ between machines, or they must stay private. If you do nothing, git status lists them all as untracked and one careless git add . commits them.

The .gitignore file tells Git which untracked files to pretend not to see. This lesson explains the pattern syntax (with the rules that surprise people), the three places an ignore rule can live, how to find out why a file is ignored, what to do when a file is already tracked, and how git clean removes untracked files when you want a fresh start.

Tracked, untracked and ignored

Git sorts every file in your working directory into one of three groups:

  • Tracked: in the last commit or in the index. Git watches it for changes.
  • Untracked: not tracked yet. It shows up in git status as ??.
  • Ignored: untracked and matched by an ignore rule. Git does not show it, and git add . skips it.

Ignoring is only about untracked files. A file Git already tracks is never ignored, whatever .gitignore says. Remember that sentence, because it explains the most common "my .gitignore does not work" question (see below).

Your first .gitignore

A .gitignore is a plain text file, usually in the root of the repository. You commit it, so every collaborator shares the rules. Each line is a pattern.

Bash Ignoring logs and build output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Before the rule file existed, every file was untracked (??, shown by directory when a whole directory is new). After adding *.log and build/, the log files and the build folder vanished from the list, and only .gitignore itself and src/ remain. The --ignored option brings them back with the !! marker so you can see what is being skipped.

Pattern syntax

Pattern Meaning
# comment A comment; blank lines are ignored
*.log Any file ending in .log, in any directory
debug.log A file or folder named debug.log anywhere in the tree
/debug.log Only in the same directory as the .gitignore (a leading slash anchors it)
build/ A directory named build anywhere (a trailing slash means directories only)
src/*.tmp .tmp files directly in src/ (a slash in the middle also anchors it)
docs/**/*.pdf .pdf files at any depth below docs/ (** matches any number of directories)
**/cache A cache entry in any directory
? Exactly one character, except /
[abc], [0-9] One character from the set or range
!pattern Negation: do not ignore what an earlier pattern ignored
\#file, \!file A backslash makes a leading # or ! literal

Two rules are worth burning into memory. First, * never crosses a slash: src/*.tmp does not match src/a/b.tmp. Use ** for that. Second, the last matching pattern wins, so order matters when you combine ignore and negation.

Matching is also relative to the folder that holds the .gitignore. A repository can contain several .gitignore files, and a file in a subfolder applies only to that folder and below. Deeper files override shallower ones.

Bash Anchoring, directories and double asterisks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Study the result. /todo.txt ignored only the top-level file; src/todo.txt is still visible. docs/**/*.pdf matched the PDF directly in docs/ and the one in docs/guides/. cache/ matched the directory src/cache, because without a leading slash a pattern can match at any depth. *.tmp matched src/app.tmp.

Why is this file ignored? git check-ignore

When a file is mysteriously ignored (or mysteriously not), ask Git. git check-ignore -v path prints the file, line number and pattern that matched.

Bash Asking Git which rule applies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Each line reads source:line:pattern<TAB>path. For important.log the matching pattern is !important.log, shown with its !: a negated pattern matched, so the file is not ignored (-v still prints negated matches). readme.txt produces no output at all, because nothing matches. The exit code tells scripts the answer: 0 if something is ignored, 1 if nothing is.

The negation trap

Negation is the source of most .gitignore frustration, and the cause is one rule: Git cannot re-include a file if a parent directory is excluded. For speed, Git does not even look inside an ignored directory.

Bash Negation that fails, and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In the first attempt the directory itself is excluded, so !logs/keep.txt has no effect and only .gitignore shows. In the second, logs/* ignores the contents of the folder while leaving the folder itself unignored, so the negation can bring keep.txt back. This is also the standard pattern for keeping an otherwise-empty directory: ignore everything inside with * and re-include a placeholder such as .gitkeep. (Git tracks files, not folders, so an empty folder cannot be committed.)

Three places for ignore rules

Location Scope Shared?
.gitignore in the repository This folder and below Yes, committed
.git/info/exclude This repository only No, stays on your machine
core.excludesFile (default ~/.config/git/ignore) Every repository on your machine No

Put project rules (build output, dependency folders, generated files) in .gitignore. Put personal rules in the global file: your editor's swap files, .DS_Store on macOS, Thumbs.db on Windows. That way you never have to add your own tools to every project. Use .git/info/exclude for something only you need in one repository, like a scratch notes file.

Bash A global ignore file and the local exclude file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first two files are ignored by the global file and my-notes.txt by .git/info/exclude. None of them involved a committed file, so teammates see nothing of it. On your own machine, git config --global core.excludesFile ~/.gitignore_global is a one-time setup (see Installing and Configuring Git).

"My .gitignore does not work": tracked files

You added a file to the repo, then later wrote its name in .gitignore, and Git keeps showing changes to it. That is the rule from the beginning: ignore rules apply only to untracked files. To make Git forget a tracked file without deleting it from your disk, remove it from the index with git rm --cached.

Bash Un-tracking a file that was committed by mistake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

After git rm --cached .env, the status shows D .env in the index (staged for deletion) while the file stays on disk and, with the ignore rule in place, no longer appears as untracked. Commit it and the file is out of the current snapshot for good.

This does not remove the file from history. The old commits still contain API_KEY=abc123, and anyone who clones can read it. If the file held a real secret, treat the secret as leaked: rotate the password or key first, and only then consider rewriting history (see Amending, Splitting and Rewriting Commits). The right habit is to add .env to .gitignore before the first commit.

If you need a tracked file to stay in the repository but want Git to stop noticing your local edits (for example a config template you customize), git update-index --skip-worktree path does that. It is a fragile tool, because the next pull that touches the file can confuse it, so prefer committing a config.example and ignoring the real config.

Cleaning untracked files: git clean

Ignored and untracked files pile up: build output, test artifacts, experiments. git clean deletes untracked files for you. It permanently deletes files that were never committed, so Git cannot get them back. For that reason it refuses to run without -f (force), and the careful workflow is always dry-run first.

Option Effect
-n (--dry-run) Only list what would be removed
-f Actually delete (required unless clean.requireForce is changed)
-d Include untracked directories
-x Also remove ignored files (a fully clean checkout)
-X Remove only ignored files
-i Interactive menu
Bash git clean: dry run first

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notice what each flag adds: plain -n only sees notes.txt; -d brings in the scratch/ directory; -x adds the ignored run.log. The final git clean -fd deleted the untracked files and directory, and left the ignored run.log alone. Tracked files are never touched. Make git clean -n... a reflex; it is the Git equivalent of "look before you leap" (see also Undoing Things).

Good habits

  • Create .gitignore in the very first commit, before generated files exist.
  • Start from a language or framework template (Node, Python, Java, Laravel and others each have well-known lists) and trim it to your needs. Always keep secrets (.env, key files) and dependency folders (node_modules/, vendor/, .venv/) in it.
  • Do not ignore lock files such as package-lock.json or composer.lock in applications; they make builds reproducible.
  • Keep personal tool files out of the project's .gitignore and in your global file.
  • Test a rule with git check-ignore -v and git status --ignored before you trust it.
  • One rule per line, with comments for anything surprising.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You added secrets.txt to .gitignore, but git status still shows modifications to it. Why?

    A tracked file is never ignored. Run git rm --cached secrets.txt and commit to stop tracking it (the old history still contains it).
  2. 2. What does the pattern /todo.txt match?

    A leading slash anchors the pattern to the folder that holds the .gitignore.
  3. 3. Why does the pair 'logs/' then '!logs/keep.txt' fail to keep logs/keep.txt?

    Git does not look inside an excluded directory. Use 'logs/*' to ignore the contents, then negate the file.
  4. 4. Which command safely shows what git clean would delete, including untracked directories?

    -n is a dry run and -d includes directories. Never run -f before looking at the dry run.
  5. 5. Where should rules for your editor's swap files go?

    Personal tool files belong in your global ignore file, so they are ignored in every repository without cluttering shared .gitignore files.

Summary

  • .gitignore hides untracked files; it never affects files that are already tracked.
  • Patterns: * does not cross /, ** does, a leading / anchors, a trailing / means directories, ! negates, and the last matching rule wins.
  • Git cannot re-include a file inside an excluded directory; ignore dir/* instead of dir/.
  • Project rules go in .gitignore, personal rules in the global excludes file, private repo-only rules in .git/info/exclude.
  • git check-ignore -v path tells you which rule matched; git status --ignored lists ignored files.
  • git rm --cached file stops tracking a file but keeps it on disk; history still contains it.
  • git clean -n previews, -f deletes untracked files for good, -d includes directories, -x includes ignored files.

Next: Undoing Things: restore, reset and revert Basics