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

  1. First things first
  2. Removing unwanted files
    1. Remove all files
    2. Remove a single file
  3. Warning - RM command
  4. Re-add your files

First things first

Before proceeding, please make sure all your changes are committed. Do not forget about the .gitignore file.


Removing unwanted files

Now that we have everything set up, we must remove those unwanted files.

Remove all files

To remove all files that should have been ignored, run this command inside your repo folder:

1
git rm -r --cached .

  • The rm command stands for remove.
  • The --cached option is used to remove files only from the index. So your files won’t be deleted from your file system.
  • The . (dot) after the word cached means that all files will be untracked.

Remove a single file

That said, if you wish to untrack a single file, you could run the same command but with a different ending:

1
git rm -r --cached script.php

In the example above, the file script.php would be untracked. And everything else should remain untouched.

Warning - RM command

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 --dry-run or -n flag. These will prevent anything from actually happening, so you can see what would be the output of your command.

Re-add your files

We need to re-add the files and commit them.

1
git add . && git commit -m "fix ignored files"

Now that you have a clean repository, don’t forget to push the changes!