waterling waterling - 2 years ago 115
Git Question

How to create branch from several commits back?

I'm fairly new to git.

Currently I have the commits depicted below, which have been pushed to remote.
only 1 branch

I created a branch (branch1) when I had to start building a ui.
But I realized that I should have made a second branch when I worked on another feature (in green).

How do I get from my current setup to the following setup? If it makes things easier, I'm working on with no other collaborators.

separate branches

All the answers worked, I accepted the first one that was submitted, but used a combination of the answers. To undo commits , we can use the interactive rebase tool (Deleting a commit in Between other commits).

Answer Source

Don't cherry-pick. Use git-rebase.

Here's where you are right now:

enter image description here

1) Create a new branch at the head of branch1:

git branch branch2

enter image description here

2) Reset branch1 to where its head should be:

You can use either git log to find the hash of the last good commit, or (in the case of my example) use HEAD~2 to go back two commits.

git reset --hard <back-there>

enter image description here

3) Switch to branch2

git checkout branch2

enter image description here

4) Rebase everything from branch1 up to branch2 onto master

git rebase --onto master branch1

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download