How to move commits in a branch to another new branch in GIT?

0

Issue

I have develop git branch for my work, I created a new branch called feature1 and made commit 1,2,3, and 4.

I need to move commit 3,4 from feature1 branch to a new created branch feature2.

The commits 3,4 should be deleted from feature1 and added to a new branch feature2, so the end result should be something like feature1 with 1, and 2 branches and feature2 with 3 and 4.

Please note that at the moment I have develop and feature1 branches. feature2 not added yet.

What is the best way to achieve that? I tried git cherry-pick but wanna make sure the best way to do that.

Solution

If I understand your description correctly, your repo currently looks like this,

... -- o [develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

and you want it to look like that

         3'-- 4'[feature2]
        /
... -- o [develop]
        \
         1 -- 2 [feature1]

Correct? If so, do the following.

First, make sure you’re in a clean working state. Then, create and check out a branch called feature2 that points at the same commit as develop:

git checkout -b feature2 develop

Your repo will look as follows.

... -- o [HEAD=feature2,develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

Cherry-pick the two commits of interest (3 and 4):

git cherry-pick <commit-ID-of-3> <commit-ID-of-4>

After that, Your repo will look as follows.

         3'-- 4'[HEAD=feature2]
        /
... -- o [develop]
        \ 
         1 -- 2 -- 3 -- 4 [feature1]

Finally, check out your feature1 branch and reset it two commits back:

git checkout feature1
git reset --hard HEAD~2

Your repo will end up as desired,

         3'-- 4'[feature2]
        /
... -- o [develop]
        \
         1 -- 2 [HEAD=feature1]

and you’ll be in a clean working state.

Answered By – jub0bs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More