Git: How to remove files added later to .gitignore from history

When versioning with Git, if a particular file is later added to .gitignore, it will be ignored in the local working directory, but will still remain in the past commit history. This can lead to problems where large numbers of files are unintentionally included in the repository, causing the repository to grow in size.

To solve this problem, you can use the following command to remove specific files from past commits

git filter-branch -f --index-filter "git rm -rf --cached --ignore-unmatch *.png *.jpg *.woff" --prune-empty -- --all

This will remove the .png, .jpg, and .woff files from all previous commits.

This operation also creates a new set of commits and places them at the top of the branch. Since this process creates unnecessary files, use the following command to remove them

rm -rf .git/refs/original/ 
git reflog expire --expire=now --all 
git gc --aggressive --prune=now

This will optimize the Git database and remove unnecessary files.

For more information, please see the following links:
https://dskd.jp/archives/46.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top