Applying .gitignore retrospectively

It can happen quickly that a file was added to Git version control through a commit, even though it was intended to be excluded from version control. In Git, you use the .gitignore file to exclude files or directories from version control.

With the help of the following commands, you can retrospectively add files and directories to the .gitignore file and remove them from version control. It is important that the .gitignore file is correctly maintained initially.

First, remove all files from the index using the following command:

git rm -r --cached .

This will not remove the actual "working files". Then, add all desired files and directories back to the staging area:

git add .

Now, the actual commit needs to be performed to complete the "clean-up":

git commit -m "Applied .gitignore retrospectively"

All files and directories listed in the .gitignore file should now have been removed from the current state in version control.

Note: Please be aware that in old revisions or other branches, the files may still be present.