git cherry-pick
- Version
- 2.51
- Review
- Draft
Summary#
git cherry-pick applies the change introduced by existing commits to the current branch and records new commits. -x includes the source commit ID in the proposed message, which helps when backporting between shared branches.
Syntax#
git cherry-pick COMMIT
git cherry-pick -x COMMIT
git cherry-pick -m 1 MERGE
git cherry-pick FIRST^..LAST
git cherry-pick --continue
git cherry-pick --abort
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config user.name "Reference Example"
git config user.email example@example.invalid
git commit -q --allow-empty -m "Release 1"
git branch release
printf 'export\n' > export.txt
git add export.txt
git commit -qm "Add export feature"
printf 'bounds check\n' > fix.txt
git add fix.txt
git commit -qm "Fix bounds check"
fix=$(git rev-parse HEAD)
git switch -q release
git cherry-pick -x "$fix" > /dev/null
# Show a stable label in place of the source commit ID.
git log -1 --format=%B | sed "s/$fix/SOURCE-COMMIT/"
git ls-files
)
Expected output#
Fix bounds check
(cherry picked from commit SOURCE-COMMIT)
fix.txt
Common mistakes#
The range FIRST..LAST leaves out FIRST. Write FIRST^..LAST for a linear series that starts at a non-root commit. A range across merges can select additional commits. A merge commit requires -m with the parent number to use as its baseline. After resolving a conflict, check that the message still credits the original commit if you need that reference.
Version applicability#
Git 1.7.2 added revision ranges. Git 1.7.8 added the sequencer's --continue and --abort forms.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0