git filter-branch

Patching & Rewriting

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>
[ ] optional| or<arg> placeholder... repeatable--flag option

Examples

Remove a file everywhere

git filter-branch --index-filter 'git rm --cached --ignore-unmatch .env' HEAD

The old, slow way.


The recommended way

git filter-repo --path .env --invert-paths

git filter-repo (separate tool) does it quickly and safely.

Workflow Examples

1
Rotate the secret

First, make it useless

2
git filter-repo --path config/secret.yml --invert-paths

Remove it from history

3
git push --force --all

Replace 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

A:

It is very slow and has many pitfalls that silently corrupt the rewrite; filter-repo fixes both.