Q: You have specific code changes in one Git branch and want to move only those changes to another branch. How would you do this?
Production guide for selectively porting isolated commits and hotfixes between Git branches using git cherry-pick without merging unrelated code.
Want to master this scenario in a live sandbox? KodeKloud's Advanced Git Workflows, Rebase & Interactive Diagnostics covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Identify Commit Hash on Source Branch
Check the git log on the source branch to identify the exact commit SHAs you want to copy.
git checkout feature-branch
git log --oneline -n 5
# Output: a8f3b9c fix(auth): resolve token expiration race condition
Switch to Target Branch and Execute Cherry-Pick
Switch to the target branch (e.g. `main` or `release-v1.4`), ensure your working tree is clean, and run `git cherry-pick
git checkout main
git pull origin main
git cherry-pick a8f3b9c
Resolving Merge Conflicts (If Applicable)
If the destination branch has divergent code, Git will pause with conflict markers. Resolve conflicts in your editor, stage the files, and continue the cherry-pick.
# Check conflicting files
git status
# After resolving markers:
git add auth/token.go
git cherry-pick --continue
# (Or run 'git cherry-pick --abort' to cancel cleanly)
Cherry-Picking Multiple Commits or Ranges
To cherry-pick a contiguous range of commits from commit A to commit B: `git cherry-pick A^..B` (includes commit A up to commit B).
- Identify the commit SHA from git log on the source branch.
- Checkout the target branch and run git cherry-pick <commit-sha>.
- If conflicts occur, resolve conflict markers, stage changes, and run git cherry-pick --continue.
- Use git cherry-pick A^..B to port a contiguous range of commits cleanly.