Git Basics: Copying One Commit with Cherry-Pick
Cherry-pick applies the change from one existing commit to your current branch. It is useful when you need a specific fix without merging an entire branch.
Run these commands in Bash with Git 2.28 or newer installed. Start a fresh temporary repository for this article:
git_practice=$(mktemp -d) || exit
mkdir "$git_practice/repository"
cd "$git_practice/repository" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThe identity and signing settings apply only to this repository. Use your own identity in real projects. The temporary files remain afterward. Examples assume default Git settings; if a pager opens, press q to leave it.
Prepare a fix on another branch
printf 'port=8080
' > app.conf
git add app.conf
git commit -q -m 'Add application config'
git switch -q -c fix-port
printf 'port=9090
' > app.conf
git add app.conf
git commit -q -m 'Fix application port'
git switch -q main
printf 'Usage notes
' > README.txt
git add README.txt
git commit -q -m 'Add usage notes'
git log -1 --format=%s fix-port
cat app.confFix application port
port=8080main and fix-port now have different commits after their shared starting point. The fix exists only on fix-port.
Apply just the fix
Start with a clean working tree. git status --short should print nothing before the cherry-pick.
git status --short
git cherry-pick fix-portGit prints a commit summary. Its commit ID varies. fix-port selects the tip commit of that branch, not every commit on the branch. In a real repository, inspect the intended commit with git show and use its ID.
cat app.conf
cat README.txt
git log -2 --format=%sport=9090
Usage notes
Fix application port
Add usage notesThe fix is now on main, alongside its usage notes. Cherry-pick normally creates a new commit with a different ID because it has a different parent; it does not move or merge the source branch.
When a cherry-pick conflicts
Git stops so you can resolve the affected files. Read git status, edit the conflict markers, stage the resolved files with git add, then run git cherry-pick --continue. To abandon an in-progress cherry-pick instead, git cherry-pick --abort returns to the state before it began and discards conflict-resolution edits from that operation.
These recovery commands are alternatives for an interrupted operation; do not run them after the successful example above. A cherry-picked commit can also depend on earlier changes, so run the project’s tests even when Git reports no conflict.
References
Acknowledgements
This post was created with assistance from AI.