To watch the youtube video on this topic (including a real demo of using cherry-picking) click here.
Introduction - When To Use Git Cherry Picking
When you work with multiple branches, sometimes there are commits in one branch that you want to copy to another branch, but you can't merge/rebase branches because you only want specific commits.
For example, let's say we had an application with certain foods in it, and let's say we had a branch named "all-foods" that had commits adding features for apples, spaghetti, bananas, cake, and cherries.
Now let's say we had a branch specifically for "fruits" that had apples, but we want to also add the work from the "all-foods" to add the "banana" and "cherry" features to the "fruits" branch. We can't merge the branches because then we'd have "spaghetti" and "cake" in our "fruits" branch. The way to solve this would be to use git cherry-picking.
1. First clone the project you're working on if you don't have it already.
2. Checkout the branch with the commit you want. (I'm not sure if this is totally required but it seems good.) You can also pull if your local branch is outdated.
3. Find the commit sha's you need by checking the commit history. (It's probably easier to just look at github/gitlab/bitbucket for this step, honestly.) Copy the commit sha's that you'll need.
4. Checkout the branch you want to add the commits too. You can also pull if your local branch is outdated.
5. Add the commits you want to add to this branch using the git cherry-pick command. If you have multiple commits, just separate the sha's with a space.
6. Optionally, create a new branch if you need too. (In case you can't directly use the branch you're currently on.)
7. Push your changes to the repository.
And that's it. Now your branch has commits in it from the other branch.
Git cherry-picking is useful for taking particular commits and copying them to another branch.
It's also a huge reason to want to keep commit histories clean by grouping changes of code logically into particular commits. (In our demo, if we added the features for bananas, spaghetti, cake, and apples all in the same commit, then cherry picking wouldn't have worked.)
Hi, I'm srcmake. I play video games and develop software.
Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
License: All code and instructions are provided under the MIT License.