0
0
GitHow-ToBeginner · 4 min read

How to Use BFG Repo Cleaner in Git for Fast History Cleanup

Use bfg by running it on a bare clone of your Git repo to remove unwanted files or sensitive data from history. After running bfg, run git reflog expire --expire=now --all and git gc --prune=now --aggressive to clean up and finalize the changes.
📐

Syntax

The basic syntax of BFG Repo Cleaner involves running the bfg command with options on a bare Git repository clone. You specify what to remove or replace using flags like --delete-files or --replace-text.

After running BFG, you must run Git commands to clean and compress the repository.

bash
bfg [options] <repo.git>

git reflog expire --expire=now --all
git gc --prune=now --aggressive
💻

Example

This example shows how to remove all files named passwords.txt from the entire Git history using BFG.

bash
git clone --mirror https://github.com/user/repo.git
bfg --delete-files passwords.txt repo.git
cd repo.git
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force
Output
Using repo.git Found 1 file to delete Deleted files: passwords.txt Deleted 1 file Git reflog expired and garbage collected Forced push to remote repository
⚠️

Common Pitfalls

  • Not cloning the repo as a bare mirror: BFG requires a bare clone (git clone --mirror), not a normal clone.
  • Forgetting to run git reflog expire and git gc after BFG: This step finalizes the cleanup.
  • Not force pushing the cleaned repo: You must use git push --force to overwrite remote history.
  • Running BFG on a non-bare repo can cause errors or incomplete cleaning.
bash
Wrong:
git clone https://github.com/user/repo.git
bfg --delete-files passwords.txt repo

Right:
git clone --mirror https://github.com/user/repo.git
bfg --delete-files passwords.txt repo.git
📊

Quick Reference

CommandDescription
git clone --mirror Create a bare mirror clone for BFG
bfg --delete-files Remove files from history
bfg --replace-text Replace text patterns in history
git reflog expire --expire=now --allExpire reflog to allow cleanup
git gc --prune=now --aggressiveGarbage collect and compress repo
git push --forceForce push cleaned history to remote

Key Takeaways

Always clone your repo with --mirror before using BFG.
Run git reflog expire and git gc after BFG to finalize cleanup.
Use --delete-files or --replace-text options to specify what to clean.
Force push the cleaned repo to update the remote history.
BFG is much faster and simpler than git filter-branch for cleaning history.