How to make Git forget a tracked file now in .gitignore
📣 Sponsor
When we track a file in git, it can sometimes get cached and remain tracked, even if we add it to our .gitignore
file. This is simply because .gitignore
prevents files from being added to Git’s tracking system, but it will not actively remove those that are already tracked. This can lead to issues when you have something you no longer want to be tracked, but can’t seem to remove it from your git repository.
Fortunately, there is an easy way to fix this. git
has a built in rm
function which lets us remove cached or tracked changes. To run it, you can use the following command to remove a specific file, where [filename]
can be removed with the file you wish to stop tracking:
git rm --cached [filename]
Similarly, if an entire directory needs to be removed, use the -r
flag which means recursive, to remove an entire directory and everything within it from tracking:
git rm -r --cached [directory]
After running this command, you can then add ammend your commit and push it to your remote:
git add .
git commit -m "Removed tracked files which shouldn't be tracked"
git push
NOTE this will not remove files from your local computer, but it will remove tracking of files from your git repository. It will also remove the files from other developers computers or servers upon your next git pull
. Be careful with this command, as I accidentally deleted all images on FJOLT using it a couple of weeks ago. :)
Conclusion
In this brief guide I’ve covered how you can remove tracked files in a gitignore. If you’re interested in other useful content, check out the links below:
- Toptal’s .gitignore generation tool
- Adding a blank directory to your git repo
- The official git handbook
More Tips and Tricks for Git
- Setting upstream with Git
- How to make Git forget a tracked file now in .gitignore
- How to add a Blank Directory to your Git Repository
- How to Auto Compress Your CSS and JS with Git Hooks
- How to undo a git pull
- How to make Git ignore file permission (chmod) changes
- Git Stash - Everything about stashing changes in git
- How to force overwrite local changes with 'git pull'
- Using Git to see recent changes in specified a time period
- Resolving Git Merge Conflicts