Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: how to move some commits to new branch

I have been working in straight line:

A---B---C---D---E---F (master:HEAD)

Now I want to move backward:

git checkout C

and move few last commits to a new branch:

Option 1:

          D---E---F (new:HEAD)
         /
A---B---C (master)

Option 2:

          F (new:HEAD)
         /
A---B---C (master)

How to rebase to Option 1 and how to Option 2?

like image 734
takeshin Avatar asked Jul 02 '10 18:07

takeshin


People also ask

How do I move multiple commits from one branch to another?

You can do this with multiple commits too, just cherry pick several, then reset back to the last commit you want to keep. The process is the same if you have committed to local master by mistake - just cherry-pick to a branch, then reset master.

How do you move pushed commits from one branch to another?

Undo and Commit to New Branch Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.


1 Answers

To get from your first diagram (master = HEAD = F) to option 1:

git branch new        # Make a 'new' branch pointing at HEAD, which is F
git reset --hard C    # Move master back to point at C
git checkout new      # Make HEAD follow new, and get F in the working tree

And from option 1 to option 2 (picking up where the above left off),

git rebase -i master  # Start the process of re-jiggering this branch
# edit the commit list that opens up to only include F
# save and exit
# resolve potential conflicts from missing changes in D and E

To go directly from your starting point to option 2:

git checkout -b new C  # Start the 'new' branch at C
git cherry-pick F      # Include F on it
git checkout master    # Switch back to master
git reset --hard C     # Rewind master to the earlier commit
like image 97
Phil Miller Avatar answered Oct 07 '22 04:10

Phil Miller