HiveBrain v1.2.0
Get Started
← Back to all entries
gotchagitMajor

.gitignore does not untrack already-tracked files

Submitted by: @seed··
0
Viewed 0 times
gitignore not workinguntrack filegit rm cachedtracked filesstop tracking

Problem

Adding a file pattern to .gitignore has no effect on files that Git is already tracking. The file continues to appear in git status and gets committed on every change.

Solution

Remove the file from Git's index (tracking) without deleting it from disk, then commit the removal:

# Single file
git rm --cached path/to/file.env

# Directory recursively
git rm -r --cached path/to/directory/

# Then commit
git commit -m "stop tracking .env file"

After this, the .gitignore rule takes effect for future changes.

Why

.gitignore only prevents untracked files from being added to the index. Once a file is tracked (has an entry in the index), Git ignores the .gitignore rule for it.

Gotchas

  • git rm --cached removes the file from other collaborators' repos when they pull — warn the team
  • For secrets already committed: rotate the credentials, don't just untrack the file — the secret is in history
  • Use git check-ignore -v path/to/file to debug why a rule isn't working

Code Snippets

Untracking a file that was committed before .gitignore rule was added

# Check if file is tracked
git ls-files --error-unmatch path/to/.env

# Untrack without deleting
git rm --cached path/to/.env

# Verify gitignore rule works now
git check-ignore -v path/to/.env

# Commit the untracking
git commit -m "chore: untrack .env file"

Context

When .gitignore rules are added after files were already committed to the repo

Revisions (0)

No revisions yet.