I accidentally committed some large files, or files I never meant to commit, to Git...
- Build artifacts and cache files got mixed in
- Tried to push a file over 100MB and got rejected by GitHub (that was me this time)
- Accidentally committed a security-sensitive file (an API key or other secret)
Simply editing .gitignore and running git rm –cached isn't enough for files like these — they remain in your past commit history.
This post introduces git filter-repo (the successor to the old git filter-branch). It lets you completely remove unwanted files, including from past commits, and rewrite your repository "clean".
Things to watch out for
・Rewriting history makes the repository incompatible with existing branches, so be careful if you're sharing the repo with other developers.
・If you've already pushed to GitHub or elsewhere, you'll need to overwrite the repository with a force push (–force).
・It's strongly recommended that you take a backup before doing this.
Steps
Step 1: Install git filter-repo
macOS
brew install git-filter-repoWindows / Linux
・Download the script from the official git-filter-repo GitHub page and place it on your PATH, or install it via a package manager.
Once installed, check that git filter-repo –help runs correctly.
Step 2: Remove the unwanted files
2-1. Example: Delete a specific file
git filter-repo --path path/to/your_file.ext --invert-paths・–path: the file path you want to remove (exclude)
・–invert-paths: the option that removes the specified path from the entire history
This completely removes your_file.ext from past commits too, as if it had never existed.
2-2. Deleting an entire directory
git filter-repo --path path/to/unwanted_folder --invert-paths・This targets every file under unwanted_folder.
2-3. Deleting multiple paths at once
git filter-repo \
--path path/to/big_file_1 \
--path path/to/big_file_2 \
--invert-pathsBy continuing the command across lines with backslashes, you can remove multiple files or folders in one go.
Step 3: Check locally & force push
Once filter-repo finishes running, the rewritten history is reflected locally.
To push the changes to the remote, you'll typically need a force push.
git push origin main --force・This overwrites the remote with a new history that no longer contains the unwanted files.
・If you have collaborators, they'll need to deal with conflicts or re-cloning, so make sure to coordinate with them beforehand.
Removing files in bulk by size
If you'd rather take the blunt approach of "just remove every file over 50MB," the following command is handy too.
git filter-repo --strip-blobs-bigger-than 50M
This wipes out any file over 50MB from the history.
That said, it's a good idea to check which files were actually removed before you rely on this.
