Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a branch in two with Git?

I've made a feature branch from master and then realize at some point that it will be better to start a new branch from this branch.

So, how to split a branch in two at a specific commit ?

Let me explain with this little schema:

I have this:

master ───●──●──●──●──●──●──●──●──●──●
              \                    
               \                   
        feature ●──●──●──●──●──●──●
                         ▲         
                         │         
                    split here         

and i wish this:

master ───●──●──●──●──●──●──●──●──●──●   
              \                       
               \                      
        feature ●──●──●──●            
                          \           
                           \          
              feature-test  ●──●──●
like image 341
felixyadomi Avatar asked Mar 11 '15 09:03

felixyadomi


2 Answers

The first step is to create feature_test where feature is:

git checkout feature
git checkout -b feature-test

But you also need to reset feature to <sha1 split here>:

git checkout feature
git reset --hard <sha1 split here>

Note that if you already pushed feature, you will need to do a git push --force.
And that might prove inconvenient for other collaborators who might already have pulled from origin/feature.

like image 111
VonC Avatar answered Sep 19 '22 01:09

VonC


You can checkout the exact commit in your feature branch whence you want the new feature-test branch to begin. Then create a new branch called feature-test from that commit:

git checkout <sha1 in feature>
git checkout -b feature-test

To obtain the SHA-1 hash for your desired commit in the feature branch, you can use git log and find the commit you want. The entry will look something like this:

commit 408d94384216f890ff7a0c3528e8bed1e0b01621
Author: Yadomi <[email protected]>
Date:   Tue Mar 11 18:10:52 2015 -0700

If you want to accomplish the same thing with just one Git command, you could also try the following:

git checkout -b feature-test 408d94384216f890ff7a0c3528e8bed1e0b01621

Here, I have used the SHA-1 has from the sample Git log, but you can replace it with whatever you need.

like image 32
Tim Biegeleisen Avatar answered Sep 19 '22 01:09

Tim Biegeleisen