DEV Community

Cover image for Move commits from one branch to another
Pranav Joglekar
Pranav Joglekar

Posted on

Move commits from one branch to another

Scenario:

You encountered a production issue. Immediately you stopped doing whatever you were working on and started fixing the bug. After fixing the bug you observe that you fixed the bug on a different branch. Now you want to move a certain number of commits from a branch A to branch B.

Solution

To move a small number of commits from A to B, use the git cherry-pick command

Say, you have the following branches

Branch A

P ----- Q ----- R ------ S

Branch B

F ----- G ----- H

(Note: P, Q, R, S, F, G, H are all commit hashes/ids)

and you want to move commits Q & R to B(in front of H). You can do the following by

git checkout branchB
git cherry-pick Q
git cherry-pick R
Enter fullscreen mode Exit fullscreen mode

This will result in

Branch B

F ----- G ----- H ----- Q ----- R

Basically, we first checkout to the branch where we want to add the commits, and cherry-pick the commits we want to move, in the order in which they appear in the first branch. Ensuring that the commits being cherry-picked are in sequential order is important or can result in complications.

Like I said, this method works if the number of commits is small, but to move a large number of commits we can use a better method

git checkout <branchname where commits are to be moved>
git rebase --onto <SHA of most recent commit in branchB> <SHA of the commit before the commit that is to be moved> <SHA of the last commit that is to be moved>
git rebase HEAD <branchname where commits are to be moved>
Enter fullscreen mode Exit fullscreen mode

So, for the above example - moving Q & R to branch B, the commands would be

git checkout branchB
git rebase --onto H P R
git rebase HEAD branchB
Enter fullscreen mode Exit fullscreen mode

These two tricks should be enough for moving commits between branches.

To read more of such git tips visit my blog - https://pranavjoglekarcodes.web.app/blogs/posts/2021/git_tricks_1/

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker

I just recently did my first successful use of cherry-pick, so magical. Thanks for posting.