How to “forget” a file tracked in Git

I often do this: I hurry creating a git repository, do a quick “git add .” and commits. Afterworth, after a few more commits, I realize that I didn’t update my .gitignore file.

So you have a state where you have added a lot of files that you really don’t want to track.

I you have added node_modules/ or build/ or .idea/ you probably already noticed it. I usually start over then with “rm -rf .git” and create a new repository (unless I have pushed the old one to github already)

But sometimes you have just accidentally added some small file that you really dont want in your repo.

If this file is a secret file, with passwords, or api keys, you are in a bit of a pickle, since you must remove this file from all your commits. This solution presented here doesnt NOT do that.

Removing the complete file history is a complicated operation. I refer to Github docs on the details: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository

But to just “hide” and “untrack” a file is easy. Remember however that you can always look at an older commit to find the file. It’s not gone from the repository!

Heres how to untrack the file:

git rm --cached [filename]

then add and push the new state

git add .
git commit -m "Removed tracked files which shouldn't be tracked"
git push

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.