PREP WITH PROOF
Menu
DEVOPS / PRACTICAL GUIDE

Gitignore Not Working? Diagnose Tracked Files and Rules

Fix gitignore confusion with ls-files, check-ignore --no-index and targeted git rm --cached. Includes a tested disposable-repository lab.

THE QUICK ANSWER

Check whether the file is tracked before editing ignore patterns. Use git ls-files for index state and git check-ignore -v --no-index for rule attribution. If the intended policy is to stop tracking it, review a targeted git rm --cached change while preserving local content.

Check whether the path is already in the index

A rule in .gitignore does not stop tracking a file that is already in Git’s index. This is the first distinction to check when a generated file or local configuration keeps appearing in git status. A matching rule and a tracked path can exist at the same time; changing the pattern alone does not remove the index entry.

Start from the repository root and inspect the specific path. git ls-files shows index entries, while git status helps distinguish a tracked modification from an untracked file. Use an explicit pathname and the double-dash separator rather than a broad wildcard during diagnosis. For unusual filenames, inspect the path as Git reports it and use a machine-safe interface when scripting.

The commands below use config.local as a harmless example. If ls-files prints it, investigate tracking state before rewriting ignore rules. If it prints nothing, the file may be untracked, ignored or absent; that observation alone does not identify a matching pattern. Continue with check-ignore and confirm the file’s actual location.

Keep working-tree content and staged content separate in your reasoning. A file can have one version on disk and another in the index. Before a targeted tracking change, review staged and unstaged changes so the eventual commit contains the intended policy change without accidentally including unrelated work.

git status --short
git ls-files -- config.local
git diff -- config.local
git diff --cached -- config.local

Source: Git ls-files — inspect tracked index entries ↗

Use check-ignore to find the rule, not to guess it

git check-ignore -v reports the matching pattern with its source file and line number. That source might be a repository .gitignore, .git/info/exclude or a configured global exclude file. This is more useful than assuming that the root .gitignore is the only source involved. Inspect the reported rule before changing repository-wide behavior.

By default, check-ignore omits tracked files because exclusion rules do not govern their tracking state. Its --no-index option lets you inspect how the rules match a path without consulting the index. That makes it useful for a file previously added before an ignore rule existed, or intentionally added with force.

Read the pattern in verbose output carefully. A matching rule beginning with an exclamation mark is a negation: it can mean the path is included again. A printed line is therefore not always proof of exclusion. For a single path, quiet mode is useful when you specifically need the ignored/not-ignored exit result; handle that result deliberately in scripts.

An empty default result for a tracked path does not prove the pattern is wrong. Compare the normal and --no-index inspections, then decide whether the fix concerns tracking or rule matching. If a command returns a nonzero status, distinguish an expected no-match result from an actual error rather than suppressing every failure.

git check-ignore -v -- config.local
git check-ignore -v --no-index -- config.local
git check-ignore -v -- debug.log
git check-ignore -q -- debug.log

Source: Git check-ignore — verbose attribution and no-index ↗

Make pattern scope and directory traversal explicit

Patterns are evaluated relative to the .gitignore file that contains them, with slash placement affecting scope. A trailing slash restricts a pattern to directories. A filename-style pattern without a qualifying slash can match at multiple levels below that ignore file. Test a few intended positive and negative paths instead of treating the pattern as a regular expression.

The order of matching rules matters, including negations. However, an exception cannot re-include a file when a parent directory itself remains excluded, because Git does not traverse that excluded directory to find the file. This explains why out/ followed by !out/keep.txt does not have the intended effect.

For the small root-level out example, excluding out/* and then negating out/keep.txt leaves the parent available for traversal and preserves the chosen file. That is a different policy from ignoring the whole out directory. If the exception is deeper in a directory tree, make each required parent traversable and test the exact nested path.

Keep the source of the policy appropriate to its audience. Repository .gitignore rules can be shared with the project. .git/info/exclude can hold rules local to that repository checkout. A personal global exclude is useful for personal tooling noise, but relying on it for a required project rule makes another developer’s results different. Diagnose all sources before deciding where a new rule belongs.

# Root .gitignore example: keep one file under out
out/*
!out/keep.txt

# Ignore logs except the named example
*.log
!keep.log

Source: Git gitignore — pattern scope, precedence and exceptions ↗

Stop tracking one intended file while keeping this local copy

If the team’s intended policy is to stop versioning a particular local file, add the appropriate ignore rule and remove only that path from the index with git rm --cached. The --cached option leaves the working-tree file in place. Without it, git rm normally also removes the working-tree file; the difference is central to this workflow.

Use the dry run first and inspect the staged result afterward. The sequence below is intended for a reviewed path after you have edited .gitignore. It does not commit or push. Replace the example path deliberately, and inspect all staged changes before making a commit so unrelated staged work is not swept into the policy change.

git rm --cached has content checks. If the staged version differs in a way Git cannot safely accept, inspect the versions and resolve that state instead of immediately adding force. The command’s refusal is useful evidence about the index; it is not a reason to rebuild the entire index or discard local changes.

The local file surviving this operation applies to this working tree. A committed deletion is still a deletion in the repository snapshot, so coordinate the policy change with collaborators and deployment requirements. Provide a safe template or documented configuration source when a required file will no longer be delivered by the repository.

git rm -n --cached -- config.local
git rm --cached -- config.local
git add -- .gitignore
git diff --cached --name-status
git diff --cached -- .gitignore config.local
git status --short

Source: Git rm — cached removal and dry run ↗

Ignoring a file does not erase history or protect its contents

An ignore rule controls ordinary treatment of untracked paths; it is not an access-control mechanism. It does not remove earlier commits, copies elsewhere or artifacts already published. If a file should not have been shared, evaluate the exposure separately rather than assuming a new ignore rule repairs it.

The fixture below demonstrates the narrow history point directly: after removing config.local from the index, git show HEAD:config.local still reads the previously committed synthetic value. The script makes no history rewrite and contacts no remote. In a real incident involving credentials, follow the relevant credential-replacement and repository-remediation process; the ignore change is only one preventive step.

Avoid broad index removal as a routine response to one ignored-file problem. Removing and re-adding the entire tree can stage unrelated changes and makes the review harder. Likewise, do not use an ignore rule to conceal changes to a source file the project intentionally versions. First decide whether that path should be shared at all.

After the change, verify both sides of the policy: the intended local file remains present, and the intended tracked example or template remains tracked. Check a new checkout or a controlled onboarding workflow when other people depend on it. A clean git status in one directory is insufficient evidence that the application’s configuration story still works.

Run the full experiment in a disposable repository

The standalone Python script below creates one temporary repository and only synthetic files. It clears inherited GIT_ variables for its subprocesses, disables system/global Git configuration and supplies an empty template directory and local fixture identity. This isolates the test from the current checkout and avoids executing user hooks.

The experiment first commits a dummy config.local, then adds ignore rules and changes its local contents. It compares normal and --no-index diagnostics, log negation and the excluded-parent trap. It changes the directory rule to preserve the exception, verifies .git/info/exclude attribution, and prepares a separate staged app.py edit before removing config.local from the index.

The exact published script passed 18 checks with Git 2.51.1 and Python 3.12.14. It verified that dry run leaves tracking intact, targeted removal preserves local bytes, the unrelated staged blob stays identical, the deletion is staged, HEAD is unchanged and earlier content remains in history. The temporary repository is removed when the script exits.

These are actual Git command checks, not a custom pattern-matching simulation. The fixture does not test sparse checkout, submodules, case-insensitive filesystems, unusual pathspec characters, collaborators pulling a deletion or remote secret-removal workflows. The manual commands above are for simple reviewed filenames; do not extrapolate them into an unreviewed bulk-cleanup script.

import os
import subprocess
import tempfile
from pathlib import Path

checks = 0

def verify(value):
    global checks
    assert value
    checks += 1

with tempfile.TemporaryDirectory(prefix='git-ignore-lab-') as temporary:
    repo = Path(temporary) / 'repo'; repo.mkdir()
    templates = Path(temporary) / 'templates'; templates.mkdir()
    env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
    env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM='1')
    def git(*args, ok=(0,)):
        r = subprocess.run(['git', '-c', 'core.excludesFile='+os.devnull,
            '-c', 'core.hooksPath='+os.devnull,
            '-c', 'init.templateDir='+str(templates),
            '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid',
            *args], cwd=repo, env=env, text=True, capture_output=True, timeout=10)
        assert r.returncode in ok, (args, r.stderr)
        return r
    git('init', '-q')
    (repo/'app.py').write_text('version = 1\n')
    (repo/'config.local').write_text('dummy = 1\n')
    git('add', '--', 'app.py', 'config.local')
    git('commit', '-qm', 'Synthetic baseline')
    original_head = git('rev-parse', 'HEAD').stdout.strip()
    (repo/'.gitignore').write_text('config.local\n*.log\n!keep.log\nout/\n!out/keep.txt\n')
    (repo/'config.local').write_text('dummy = 2\n')
    (repo/'debug.log').write_text('synthetic\n')
    (repo/'keep.log').write_text('keep\n')
    (repo/'out').mkdir(); (repo/'out/keep.txt').write_text('keep\n')
    verify(git('ls-files', '--error-unmatch', '--', 'config.local').returncode == 0)
    r = git('check-ignore', '-v', '--', 'config.local', ok=(1,))
    verify(r.stdout == '')  # tracked path omitted by default
    verify('config.local' in git('check-ignore', '-v', '--no-index', '--', 'config.local').stdout)
    verify(git('check-ignore', '-q', '--', 'debug.log').returncode == 0)
    verify(git('check-ignore', '-q', '--', 'keep.log', ok=(1,)).returncode == 1)
    verify('!keep.log' in git('check-ignore', '-v', '--', 'keep.log').stdout)
    verify(git('check-ignore', '-q', '--', 'out/keep.txt').returncode == 0)
    (repo/'.gitignore').write_text('config.local\n*.log\n!keep.log\nout/*\n!out/keep.txt\n')
    verify(git('check-ignore', '-q', '--', 'out/keep.txt', ok=(1,)).returncode == 1)
    (repo/'notes.tmp').write_text('local\n')
    (repo/'.git/info').mkdir(exist_ok=True)
    (repo/'.git/info/exclude').write_text('notes.tmp\n')
    verify('.git/info/exclude' in git('check-ignore', '-v', '--', 'notes.tmp').stdout)
    # Preserve an unrelated staged edit while removing only config.local.
    (repo/'app.py').write_text('version = 2\n'); git('add', '--', 'app.py')
    staged_app = git('rev-parse', ':app.py').stdout.strip()
    local_bytes = (repo/'config.local').read_bytes()
    git('rm', '-n', '--cached', '--', 'config.local')
    verify(git('ls-files', '--', 'config.local').stdout.strip() == 'config.local')
    git('rm', '--cached', '--', 'config.local')
    verify((repo/'config.local').read_bytes() == local_bytes)
    verify(git('ls-files', '--', 'config.local').stdout == '')
    verify(git('rev-parse', ':app.py').stdout.strip() == staged_app)
    verify(git('diff', '--cached', '--name-status', '--', 'config.local').stdout.strip() == 'D\tconfig.local')
    verify(git('check-ignore', '-q', '--', 'config.local').returncode == 0)
    verify(git('show', 'HEAD:config.local').stdout == 'dummy = 1\n')
    verify(git('rev-parse', 'HEAD').stdout.strip() == original_head)
    git('add', '--', '.gitignore')
    verify('.gitignore' in git('diff', '--cached', '--name-only').stdout)
print(f'{checks} checks passed; one disposable repository; no remotes or user repo changes')

Verify the path policy rather than just hiding a status line

A successful repair has an explainable result: the path is either intentionally tracked, or it is untracked and matched by the intended exclusion rule. Record which source supplies that rule, and check the exception paths that must remain visible. Keep the staged diff narrow enough that a reviewer can see exactly what changed.

Use tracking inspection first, rule attribution second and a targeted index change only when the policy requires it. This sequence separates a wrong pattern from a previously tracked file, preserves local work and makes the repository’s future behavior predictable.

KEEP THESE THREE THINGS

Your next steps

  1. Ignore rules do not stop tracking files already in the index.
  2. Verbose check-ignore identifies the rule source; --no-index helps inspect tracked paths.
  3. A negation cannot rescue a file inside a still-excluded parent directory.
  4. Targeted index removal preserves this local copy but does not erase earlier history.

Sources & official resources

Linked resources checked on 2026-10-30. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →