Git Advanced Cheat Sheet/Rewrite history to keep a subdirectory

Create a new history containing only one subdirectory.

Section: History Rewriting

Rewrite history to keep a subdirectory

bash
bash
git filter-branch --subdirectory-filter path/to/subdir -- --all
Explanation

Older but still encountered approach for history rewriting. For large or modern repos, many teams prefer `git filter-repo` externally.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing History Rewriting
Interactive rebase last 5 commits
Open the last 5 commits in the interactive rebase todo list.
OpenIn sheetbashsame section
Amend last commit without changing message
Replace the most recent commit using the current staged changes.
OpenIn sheetbashsame section
Rebase a branch onto a new base
Move a branch from one base commit or branch to another.
OpenIn sheetbashsame section
Interactive rebase preserving merges
Rebase while preserving merge topology.
OpenIn sheetbashsame section
Cherry-pick a range without committing
Apply commit changes into the index and working tree first.
OpenIn sheetbash2 tag match
Start a bisect session
Begin a binary search to find the commit that introduced a bug.
OpenIn sheetbash2 tag match