Git | Ignoring files that have already been committed to the repo.
Sometimes we add new paths or specific files to .gitignore.
But what happens if the file or path we added to .gitignore was already tracked on the repo?
The answer is: these files will still be present in your repository index. In this article, I will show you how to correctly get rid of these files.
Table of Contents
- First things first
- Removing unwanted files
- Warning - RM command
- Re-add your files
Before proceeding, please make sure all your changes are committed. Do not forget about the .gitignore file.
Now that we have everything set up, we must remove those unwanted files.
To remove all files that should have been ignored, run this command inside your repo folder:
git rm -r --cached .
rmcommand stands for
--cachedoption is used to remove files only from the index. So your files won’t be deleted from your file system.
.(dot) after the word cached means that all files will be untracked.
That said, if you wish to untrack a single file, you could run the same command but with a different ending:
git rm -r --cached script.php
In the example above, the file script.php would be untracked. And everything else should remain untouched.
It seems pretty easy, but don’t forget that we are using the
rm command. And if you make a mistake when using it, well, that could be bad.
If you want to, it’s possible to add the
-n flag. These will prevent anything from actually happening, so you can see what would be the output of your command.
We need to re-add the files and commit them.
git add . && git commit -m "fix ignored files"
Now that you have a clean repository, don’t forget to push the changes!