0
0
GitHow-ToIntermediate · 3 min read

How to Use git filter-branch: Syntax, Example, and Tips

Use git filter-branch to rewrite Git commit history by applying filters to each commit. The command lets you change author info, remove files, or modify commit messages across branches. Run it with options like --tree-filter or --env-filter to specify the changes you want.
📐

Syntax

The basic syntax of git filter-branch is:

  • git filter-branch [options] -- [revision range]

Key parts explained:

  • options: Specify the type of filter like --tree-filter to modify files or --env-filter to change environment variables like author info.
  • --: Separates options from revision range.
  • revision range: The commits to rewrite, e.g., HEAD or --all for all branches.
bash
git filter-branch [options] -- [revision range]
💻

Example

This example removes a file named secret.txt from all commits in the current branch:

bash
git filter-branch --tree-filter 'rm -f secret.txt' HEAD
Output
Rewrite 1234567 (1/10) rm 'secret.txt' Rewrite 89abcde (2/10) rm 'secret.txt' ... Ref 'refs/heads/master' was rewritten
⚠️

Common Pitfalls

  • Running git filter-branch rewrites history, so it changes commit hashes. Avoid using it on shared branches without coordination.
  • It can be slow on large repos because it processes every commit.
  • Always back up your repo before running it.
  • Use --force if you want to overwrite previous filter-branch runs.
bash
git filter-branch --tree-filter 'rm -f secret.txt' HEAD
# Wrong: running without backup or on shared branch

# Right: backup first
cp -r repo repo-backup

# Then run filter-branch
📊

Quick Reference

OptionDescription
--tree-filter ''Run command on each commit's files to modify content
--env-filter '