GIT: Forget Previously Tracked File

Apr 9, 2021 min read

There are times we mistakenly check in certain files into our repository, or change our mind after a file has already been committed. I see this most often with .env or config files that contain sensitive information like passwords or API keys. These files are needed for the application to run, but shouldn’t be checked into version control.

If you have checked in a file with sensitive information, the very first thing you should do is change those values immediately. Even if your repository is private and only your team has access, those values should be considered compromised and should be changed to prevent unauthorized data access.

Steps to tell GIT to “forget” about a file or directory:

Add the file or directory to the .gitignore file.

.env >> .gitignore

Remove the file(s) from the GIT cache.

git rm --cached <file>

Remove an entire directory, remove recursively

git rm -r --cached <directory>