How to add tracked files to .gitignore

How to add tracked files to .gitignore

At one point or the other, you might have committed some files or folders to your remote repo that after several commits you decide that you no longer want to track those files or folders and you try to edit directly the .gitignore file but it doesn't work or sometimes you go as far as cutting the folder pushing a commit and paste the folder and add the folder to .gitignore then push as though it were a new one.

The reason for this issue is that the rules in your .gitignore only apply to untracked files, therefore, subsequent edits would apply to the following files or folders and not the old ones.

Here is a hack on how to fast-track that process.

  1. Add the directory you want to remove to your .gitignore.
  2. Then run this
    git rm -r --cached directory-to-remove
    git commit -m 'feat: remove " directory-to-remove" from remote repo'
    git push origin master
    

Notes

  1. git rm -r --cached directory-to-remove
    

    This command provides you with a preview of what is getting deleted from your git cache.

  2. However, this doesn't remove the history of the file or folder from your git history and make it appear as though it never existed. To do that you can check out BFG Repo Cleaner or you use git filter-branch. Check out this guide on how to use it.

Have fun!