Last Updated: February 25, 2016
·
3.187K
· jan0sch

Howto split a git repository into two

Sometimes you'll want or have to split a git repository into two. This is usually a sign of not thinking forward enough but hey sh.. happens. If your repository is structured in a way that you just need a subdirectory of it into a new repository you can follow the steps below.

We assume a repository foo that contains a folder foobar that shall be a new repository called bar.

% git clone --no-hardlinks foo bar
% cd bar
% git filter-branch --subdirectory-filter foobar HEAD  -- --all
% git reset --hard
% git gc --aggressive
% git prune

If you're working with remote repositories you'll have to delete the old remote origin and set a new one.

% git remote rm origin
% git remote add origin git@example.com:bar.git
% git push -u origin master

Now we'll cleanup the original repository.

% cd foo
% git filter-branch --tree-filter "rm -rf foobar" --prune-empty HEAD
% rm -rf foobar
% git push -f

Now you should now have two seperate repositories.