gitignore Only Applies to Files Git Does Not Track Yet
Adding a committed file to .gitignore changes nothing: Git keeps tracking it and keeps recording its changes. .gitignore only stops untracked files from being added. To stop tracking a file while keeping it on disk, remove it from the index with git rm --cached, then commit.
The Three Trees
| Tree | Holds |
|---|---|
| Working directory | the files on disk |
| Index (staging area) | the proposed next commit |
HEAD (repository) |
the last commit |
A tracked file is one that is in the index. .gitignore is consulted only when deciding whether to add an untracked file, so it never applies to a file already in the index.
Untracking Without Deleting
echo ".env" >> .gitignore
git rm --cached .env # -r for a folder: git rm -r --cached node_modules
git commit -m "Stop tracking .env"
git rm alone would also delete the file from disk; --cached removes it from the index only. After the commit the file stays in the working directory, matches .gitignore, and shows up as ignored.
References
- DevOps and Infrastructure as Code MOC - hub for DevOps and Git notes.
- Git documentation: gitignore - "files already tracked by Git are not affected".
- Git documentation: git rm - the
--cachedoption. - GitHub Docs: Removing sensitive data from a repository - rewriting history and rotating secrets.
Review cards
Flashcard Why does adding a committed file to `.gitignore` not change anything?
Because .gitignore only affects untracked files and does not alter the state of tracked files, which are already being monitored by Git.
Flashcard What happens if you use `git rm --cached` on a tracked file?
It removes the file from the index but keeps it in the working directory, making it appear as ignored in the repository.
Quiz How do you stop tracking a committed file while keeping it on disk?
- git rm --cached the file, then commit
- Delete it and add it to .gitignore
- git rm without --cached
- Add it to .gitignore and commit
git rm --cached removes it from the index only. .gitignore alone changes nothing, because it only applies to files Git doesn't track yet.