Git Cherry Pick: What It Is and How to Use It
git cherry-pick is a command that lets you copy a specific commit from one branch and apply it to another branch. It helps you pick only the changes you want without merging entire branches.How It Works
Imagine you have two branches in your project, like two different paths in a garden. Sometimes, you make a change on one path (branch) that you want to bring over to the other path without taking everything else along. git cherry-pick lets you do exactly that by copying a single change (commit) from one branch and applying it to another.
It works by taking the exact changes recorded in a commit and replaying them on your current branch. This is different from merging, which combines all changes from one branch to another. Cherry-picking is like picking a single ripe cherry from a tree instead of shaking the whole branch.
Example
This example shows how to cherry-pick a commit from one branch to another.
git checkout main
# Suppose commit abc123 is a useful fix on feature-branch
git cherry-pick abc123
# The changes from commit abc123 are now applied to your current branchWhen to Use
Use git cherry-pick when you want to apply a specific fix or feature from one branch to another without merging all changes. For example:
- You fixed a bug on a development branch and want to apply just that fix to the main branch.
- You want to bring a feature from a feature branch to a release branch without merging unfinished work.
- You need to selectively copy commits for hotfixes or patches.
This helps keep branches clean and focused on their purpose.
Key Points
- Selective copying: Cherry-pick copies individual commits, not whole branches.
- Replay changes: It applies the exact changes from the chosen commit.
- Conflict handling: You may need to resolve conflicts if changes overlap.
- Useful for hotfixes: Quickly apply fixes across branches.