40

I have a bunch of commits for an OS project and I want to pull out just the last say 20 commits into another branch so I can pull request.

How could I do this? The reason being is I have maybe 150 commits, but most of those are for a much larger contribute, which isn't ready yet. But the next version is being released soon.

Thanks!

Steven
  • 13,250
  • 33
  • 95
  • 147

2 Answers2

110

You can do this with cherry-pick. If your history of long_branch looks like this:

A-B  <-- master
   \
    C-D-E-F-G-H  <-- long_branch

and you want to move the contents of, say, F through H to a different branch, say, short_branch, which is based off of master:

git checkout master -b short_branch

which gives

A-B  <-- master, short_branch
   \
    C-D-E-F-G-H  <-- long_branch

then... (note that the commit range is E..H; the left side is non-inclusive for the range)

git cherry-pick E..H

which gives:

    F'-G'-H'  <-- short_branch
   /
A-B  <-- master
   \
    C-D-E-F-G-H  <-- long_branch

Note that I'm referring to the new commits as F', G', H' - this is because while they will contain the same effective changes as F, G, and H, they won't be the actual same commits (due to different parents + commit times).

Amber
  • 507,862
  • 82
  • 626
  • 550
  • 2
    Wow I would upvote this twice if I could. A very concise, non-esoteric example that is extremely understandable and covers the gotchas. Thanks! – dudewad Aug 14 '19 at 05:19
12

Do you want the 20 commits to remain on the current branch? If not, then keep a reference to the current branch back 20 commits with:

git checkout -b current_branch_save current_branch~20

Then, move the last 20 commits with rebase

git checkout current_branch
git rebase --onto another_branch current_branch~20 current_branch

Now you've got current_branch_save with your ~100 'not quite ready' commits and current_branch on another_branch with the last 20.

GoZoner
  • 67,920
  • 20
  • 95
  • 145