How to copy commits from one branch to another?

You should really have a workflow that lets you do this all by merging:

- x - x - x (v2) - x - x - x (v2.1)
           \
            x - x - x (wss)

So all you have to do is git checkout v2.1 and git merge wss. If for some reason you really can’t do this, and you can’t use git rebase to move your wss branch to the right place, the command to grab a single commit from somewhere and apply it elsewhere is git cherry-pick. Just check out the branch you want to apply it on, and run git cherry-pick <SHA of commit to cherry-pick>.

Some of the ways rebase might save you:

If your history looks like this:

- x - x - x (v2) - x - x - x (v2.1)
           \
            x - x - x (v2-only) - x - x - x (wss)

You could use git rebase --onto v2 v2-only wss to move wss directly onto v2:

- x - x - x (v2) - x - x - x (v2.1)
          |\
          |  x - x - x (v2-only)
           \
             x - x - x (wss)

Then you can merge! If you really, really, really can’t get to the point where you can merge, you can still use rebase to effectively do several cherry-picks at once:

# wss-starting-point is the SHA1/branch immediately before the first commit to rebase
git branch wss-to-rebase wss
git rebase --onto v2.1 wss-starting-point wss-to-rebase
git checkout v2.1
git merge wss-to-rebase

Note: the reason that it takes some extra work in order to do this is that it’s creating duplicate commits in your repository. This isn’t really a good thing – the whole point of easy branching and merging is to be able to do everything by making commit(s) one place and merging them into wherever they’re needed. Duplicate commits mean an intent never to merge those two branches (if you decide you want to later, you’ll get conflicts).

Leave a Comment