How do you cherry-pick a commit from one branch to another?
Posted by RoseHrs
Last Updated: June 06, 2024
Cherry-picking a commit in Git allows you to apply the changes introduced by a specific commit from one branch to another. Here's how you can do it step-by-step:
Step-by-Step Cherry-Picking
1. Identify the Commit Hash: First, you need to find out the hash of the commit you want to cherry-pick. You can use the following command to list the commits in your current branch:
git log
Note the commit hash (a 40-character string) of the commit you want to cherry-pick. 2. Switch to the Target Branch: Check out the branch where you want to apply the commit.
git checkout target-branch
Replace target-branch with the name of your branch. 3. Cherry-Pick the Commit: Now you can cherry-pick the commit using its hash.
git cherry-pick <commit-hash>
Replace <commit-hash> with the actual hash of the commit you want to cherry-pick. 4. Resolve Conflicts (if any): If there are conflicts during the cherry-pick, Git will prompt you to resolve them. You can: - Edit the files that show conflicts. - After resolving, mark the files as resolved:
git add <file-with-conflicts>
- Then, complete the cherry-pick with:
git cherry-pick --continue
5. Complete the Cherry-Pick: If there are no conflicts, the cherry-pick will be completed automatically and the changes will be applied to your current branch. 6. Push the Changes: If you are satisfied with your changes, you can push them to the remote repository:
git push origin target-branch
Example
Here's a practical example of the commands you would run:
# List commits and find the desired commit hash
git log 

# Switch to the branch you want to apply the commit to
git checkout feature-branch

# Cherry-pick the commit
git cherry-pick abc1234 # replace abc1234 with your actual commit hash
Note
- When cherry-picking, be cautious of potential merge conflicts. - Cherry-picking can lead to duplicated commits if