git filter-branch --subdirectory-filter <dir_folder>

Rewrite history so only the contents and history of a specific subdirectory remain in the repository.

This command is useful when you want to extract a subfolder out of a larger repository and turn it into its own project while preserving its commit history.

This command runs git filter-branch with the --subdirectory-filter option, which rewrites the entire commit history so that only the contents of the specified <dir_folder> are kept at the root of each commit, discarding files and folders outside that path and dropping commits that did not touch that subdirectory. The --subdirectory-filter <dir_folder> flag tells Git to treat <dir_folder> as if it were the repository root in every commit, effectively trimming the tree so that after the rewrite, the files that used to be under <dir_folder> now appear at the top level. You can optionally add flags like -f (or its long form) to force the rewrite even if there are existing backup refs, and you can restrict which branches are rewritten by appending branch names after the filter options instead of rewriting all branches by default.

You can extend this approach by combining --subdirectory-filter with other filter types such as --prune-empty to automatically drop commits that become empty after removing other paths, or by adding refspecs like -- --all to ensure all references (branches, tags) are rewritten. A more modern and faster alternative is to use git filter-repo with a similar effect, for example git filter-repo --subdirectory-filter <dir_folder>, which is recommended over git filter-branch for performance and maintainability, or to combine this with git remote add and git push to move the filtered history into a new standalone repository or a different remote.

Examples:

  • git filter-branch --subdirectory-filter src/app
  • git filter-branch --subdirectory-filter backend

Welcome to GitExamples!

Sign in to enable bookmarking, reminders, progress-tracking and more...