64

So I created a branch off of another branch I was already creating, and now when I try to merge the branches into master, I have run into the situation where I have to merge both branches.

Here is a diagram

Master->

 ->Branch 1  -> Branch 2

I want to be able to merge just the changes on branch 2 onto master without having to merge the changes on Branch 1 if that makes sense. I looked into reset and revert, but it seems like these things will delete all the changes I made with branch 2. Any ideas?

Thanks

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Levi S
  • 739
  • 1
  • 5
  • 5

2 Answers2

102

Try git rebase --onto with the following syntax:

To put branch2's changes on to the master without including branch1's

git rebase --onto master branch1 branch2

Relevant output from git help rebase:

Here is how you would transplant a topic branch based on one branch to another, to pretend that you forked the topic branch from the latter branch, using rebase --onto.

First let’s assume your topic is based on branch next. For example, a feature developed in topic depends on some functionality which is found in next.

              o---o---o---o---o  master
                   \
                    o---o---o---o---o  next
                                     \
                                      o---o---o  topic

We want to make topic forked from branch master; for example, because the functionality on which topic depends was merged into the more stable master branch. We want our tree to look like this:

              o---o---o---o---o  master
                  |            \
                  |             o'--o'--o'  topic
                   \
                    o---o---o---o---o  next

We can get this using the following command:

git rebase --onto master next topic

Keep in mind the risks and pitfalls of rebasing, mentioned here: http://git-scm.com/book/en/Git-Branching-Rebasing

Adrian W
  • 4,563
  • 11
  • 38
  • 52
somesh
  • 2,509
  • 3
  • 16
  • 24
  • I'm here because I did the same thing as OP. I.e. I accidentally branched my local features/feature1 as features/feature2. And should have braned develop as features/feature2. It looks like rebase --onto will do what I want, but should I check-out one of the three branches before running rebase? And I suppose I need to commit my change to features/feature2 first?? – Ken Hadden Jan 17 '20 at 19:54
13

One way to do it is, use cherry-pick. Do a git log branch2 and find the commit id's you want and then switch to master branch using git checkout master then use git cherry-pick <commit_id>

Refer to this post for more details

How to merge a specific commit in Git

Community
  • 1
  • 1
user376507
  • 2,004
  • 1
  • 19
  • 31