Split commits into two branches
Asked Answered
S

2

9

I am on a branch named feature-1. I run git log, which shows me a bunch of commits:

commit <HASH-1>
…
commit <HASH-2>
…
commit <HASH-3>
…
commit <HASH-4>
…

Now I want commit <Hash-3> and older commits to be on feature-1 branch, whereas commit <HASH-2> and newer commits to be on a new branch named feature-2. How can I do that?

Sheatfish answered 6/7, 2015 at 9:52 Comment(0)
H
9

This is a great use case for the interactive rebase feature.

First create the new feature-2 branch on the same commit as your current HEAD (which points to feature-1) by running git branch feature-2.

Now run git rebase -i origin/master. This will open your $EDITOR with something like this:

pick 3182a77e Commit 1
pick 6f717613 Commit 2
pick f30c1e92 Commit 3
pick b1c13f14 Commit 4

Remove the first two lines and save the file. Now git will recreate the commits so that feature-1 only contains the commits you want.

Now run git checkout feature-2 and then again git rebase -i origin/master. You will again see all 4 commits, but this time keep only the ones you want in feature-2. Save the file again and you're done.

Hospers answered 18/1, 2020 at 19:34 Comment(0)
B
3

Checkout the commit that you want to be under your new branch and then create branch from this point.

git log --oneline ...

commit <HASH-1>
commit <HASH-2>
commit <HASH-3>
commit <HASH-4>


git checkout -b feature-1 <HASH-3> 
git checkout -b feature-2 <HASH-2> 

and so on,

You simply checkout any commit you want (any point in your history) and then you create branch at this point


How to create branches?

Branches can be created in several ways:

Create branch from the current commit

  • By creating branch ant not checking them out
    git branch < branch_name>

  • By creating and switching to a new branch

    git checkout -b <branch_name>
    git checkout -t <branch_name>
    

The default SHA-1 if not specified is the HEAD

Create branch from selected commit

By adding sha-1 to the checkout command you "set" the commit that your branch will be created from.

    git checkout -b <branch_name> <sha-1>
    git checkout -t <branch_name> <sha-1>
Bigname answered 6/7, 2015 at 10:34 Comment(2)
what is -t in git checkout -t ?Sheatfish
-t = When creating a new branch, set up "upstream" configuration (track)Bigname

© 2022 - 2024 — McMap. All rights reserved.