Removing a file permanently from Git

For those of you using Git, I’d like to share a valuable procedure.

Sometimes it might be necessary to remove a file or folder permanently from a Git repository AND from the history so that it isn’t possible to ever revert back to the file.

For example, you’ve committed files that contain sensitive information (e.g. a password), or perhaps you’ve incorrectly committed a massively large file that is taking up a lot of storage and is being dragged along each time new users pulls your repository.

This happened recently to me in one of my public GitHub repositories, so to save you the trouble should it ever happen to you, here are the steps:

Step 1: In the command prompt go to the root folder of the repository.
Step 2: git filter-branch -f --index-filter “git rm -rf --cached --ignore-unmatch FULL_PATH_TO_FILE_OR_FOLDER” HEAD
Step 3: Delete the .git/refs/original/ folder
Step 4: git reflog expire --expire=now --all
Step 5: git gc --aggressive --prune=now
Step 6: git push origin --force --all
Step 7: git push origin --force --tags

Any trace of the file will now be gone, and all the storage used by the file or folder will be reclaimed. I reduced the size of my own repository from 60MB to 12MB after removing the erroneous files.

PS. Use this at your own risk.

When doing the above, make sure if you have other developers, that they no longer push from their local tree, otherwise it will appear again. Everyone needs to pull down a fresh copy of the repo.