227

I have BranchA which is 113 commits ahead of BranchB.

But I only want the last 10 or so commits from BranchA merged into BranchB.

Is there a way to do this?

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
  • 6
    possible duplicate of [How to merge a specific commit in git](http://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git) – chharvey Mar 25 '14 at 10:32

2 Answers2

341

The git cherry-pick <commit> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.

Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)

Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.

grane2212
  • 764
  • 1
  • 10
  • 29
ewall
  • 27,179
  • 15
  • 70
  • 84
  • 4
    Question: say commit `A` is branched off of `master` and you do some work on it, creating child commits `B` through `E`. Say `E` only has 1 line added from `D`. If you `git cherry-pick E` into `master`, does it apply *all* the changes from `A` through `E` into the `master` branch, or does it *only* apply the change from `D` to `E`, namely, it adds only that 1 line to `master`? If the case is the former, how do I achieve the latter? (aside from manually copying and pasting) – chharvey Mar 25 '14 at 10:44
  • 11
    git cherry-pick -n If you don't want the cherry pick auto-committed. – Ben Flynn Jun 19 '15 at 18:09
  • 2
    little side-note: you can manually do it on github desktop (right click on specific commit to cherry pick) -- then it's intuitive :) – jjrr Jul 07 '21 at 13:00
10

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
Seth Reno
  • 5,350
  • 4
  • 41
  • 44