Exclude files/folders already added to GIT repository using .gitignore

Let's assume that we have already added (committed and pushed) files to the git repository (locally and remotely). And then we added them to the .gitignore file. These files (folders) will still be present in our repository index and will continue to be updated and tracked - these files are already in the index and the .gitignore is ignored in this case. Below I will show how to get rid of such files.

How to completely clean the GIT repository (clear the index)

Step 1: Commit all changes

Before continuing, make sure all changes are committed, including files from .gitignore.

Step 2: Remove everything from the repository

To clean the repository, use:

git rm -r --cached .
  • rm — means remove.
  • -r — allows recursive removal.
  • --cached — will only remove files from the index, not physically.
  • . — indicates that all files will be removed.

The rm command is ruthless. Therefore, you can make a "fake" request, to do this, add the -n or --dry-run flag to see what the command will do.

Step 3: Add everything again

git add .

Step 4: Commit

git commit -m ".gitignore reactivated"

That's it. Your repository is clean smile

Push the changes to the remote server to also remove all unnecessary files there.

How to remove a specific file from the GIT track list

Sometimes it is necessary to remove a file or several files from the track list of a GIT repository. For example, when a file accidentally got into the track list, then you added it to .gitignore, and now you need to remove it from git, but without physically deleting the file. This can be done with the following command:

git rm --cached www/composer.lock