Working with Git – Cherry Picking Commits
The perfectly named git cherry-pick command is similar to git merge in that you can copy commits from a different branch into your current branch. However, where merging will copy all of the commits from the other branch, cherry-pick is useful when you only want to copy specific commits into your branch.
The simplest use case is to copy one commit from a different branch into your branch. The command is:
git cherry-pick <commit>
Here we have a master branch with 7 commits, and a temp branch that only has the initial commit from master. I want to copy one of the commits from master into temp.
- The commit I want to copy
- The list of commits in temp. You can see just the one is there.
- The cherry-pick command.
- Checking the log of temp after the cherry-pick shows that the commit is now part of the temp branch.
One important thing to note is that the cherry-picked commit has a different ID than the corresponding commit in master. This is because a commit’s ID is based on the code change AND the parent commit ID. So even though the commit we copied in played-back the same code change in temp, it has a different parent in temp than it did in master.
To copy multiple commits, just include each of the commit ID’s in the cherry-pick command:
- cherry-pick with the 2 commits to copy. Since we are copying the commit that is at the top of master, we can use the branch name instead of the commit ID.
- The 2 commits copied into the temp branch.
Some other useful options you can use with cherry-pick are
- Including -e allows you to edit each of the copied commit messages
- Including -x automatically edits each commit message to include the original commit ID
- Including -n will play-back the changes in each of the commits, but will not actually create any new commits in your branch. This will leave your branch in a state of having staged, un-committed changes. This option is useful if you want to squash the copied commits into one commit.
Other options and details about the cherry-pick command can be found at these sites: