git filter-branch
Rewrite history with filters (deprecated — use git filter-repo)
The 'git filter-branch' command rewrites every commit of a branch through filters — for example to remove a file from all history. It is slow, easy to misuse and officially discouraged: Git itself prints a warning and recommends git filter-repo instead. Like any rewrite, it gives every commit a new hash, so everyone must re-clone or reset.
Synopsis
git filter-branch [--index-filter <cmd>] [--tree-filter <cmd>] [--msg-filter <cmd>] [--] <rev-list>Examples
Remove a file everywhere
git filter-branch --index-filter 'git rm --cached --ignore-unmatch .env' HEADThe old, slow way.
The recommended way
git filter-repo --path .env --invert-pathsgit filter-repo (separate tool) does it quickly and safely.
Workflow Examples
Rotate the secretFirst, make it useless
git filter-repo --path config/secret.yml --invert-pathsRemove it from history
git push --force --allReplace the remote history
Troubleshooting
Cannot create a new backup
Cause: refs/original exists from a previous run
Delete it (git update-ref -d refs/original/refs/heads/main) or use -f
Tips & Pitfalls
Best Practices
- ✓Use git filter-repo instead.
- ✓Back up the repository before any rewrite.
Common Mistakes
- ✗Rewriting shared history without telling the team.
- ✗Thinking a rewrite makes a leaked secret safe — rotate the secret.
FAQ
It is very slow and has many pitfalls that silently corrupt the rewrite; filter-repo fixes both.