Search code examples
gitsplitbranchrebasecut

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  ●──●──●

Solution

  • 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.