Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 78 ยท Branching and Merging

Cherry-Pick and Applying Commits

Learn git cherry-pick: copy single commits or ranges to another branch, backport fixes with -x, stage without committing, resolve conflicts and avoid duplicates.

A merge brings in everything a branch has done. Sometimes that is far too much. You fixed a bug on a feature branch, and the fix is needed on the release branch right now, but the other twelve half-finished commits on that feature branch are not. You want to take one commit and apply it somewhere else. That is what git cherry-pick does.

Cherry-picking is one of those commands that looks trivial and then surprises you in production: the copy is a brand-new commit with a different hash, the same change can end up applied twice, and a conflict in the middle of a range leaves you in a half-finished state. This lesson builds the mental model first, then goes through the options professionals use every week: -x, -n, ranges, merge commits, --continue and --abort.

What cherry-pick really does

A commit is a snapshot, but Git can also look at it as a change: the difference between the commit and its parent. git cherry-pick <commit> takes that difference and applies it on top of your current HEAD, then records the result as a new commit with the same author, the same author date and the same message.

TEXT
before:                          after  git switch main; git cherry-pick F2

main:     A---B                  main:     A---B---F2'
               \                                \
feature:        F1---F2---F3     feature:        F1---F2---F3

F2' has the same change, the same message and the same author as F2, but it has a different parent (B, not F1), so it has a different hash. Git does not remember that F2' was copied from F2. To Git they are two unrelated commits that happen to make the same edit. Keep that sentence in mind: nearly every cherry-pick pitfall follows from it.

Internally, cherry-pick performs a three-way merge in which the "base" is the picked commit's parent, "ours" is your current HEAD, and "theirs" is the picked commit. If you want to know how that merge works, see How Merge, Rebase and Diff Work Inside.

Picking one commit

Here is the smallest useful example. A feature branch contains a bug fix sandwiched between unrelated work. We copy only the fix to main.

Bash Copy one commit to another branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Only the fix moved. main has a new commit on top, feature.txt is not there, and app.txt contains the corrected line. In the graph you can see two commits with the same message and different hashes: the original on feature and the copy on main.

Cherry-pick keeps the original author and author date, but the committer becomes you, with the time of the cherry-pick. That is why we set GIT_COMMITTER_DATE in the example: git log --format=fuller shows both identities.

Recording where a copy came from: -x

Because Git forgets the relationship, a human reading main later has no idea that a commit was copied or from where. The -x option appends a line to the message with the original hash:

TEXT
Fix typo in line 2

(cherry picked from commit 3f2a9c1...)

Use -x whenever you cherry-pick between long-lived, shared branches such as main to release/1.4. When someone later asks "did the fix reach the release?", you can git log --grep for the hash. Skip it when you pick from a private branch that will be deleted: the hash would point at a commit nobody can reach.

Bash Backporting a fix to a release branch with -x

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at the output: the cherry-pick conflicted. The fix changed price = 10 to price = 12, but it was made on top of a file that also had the new discount line, and the release branch does not have that line. Because the surrounding context differs, Git cannot apply the change by itself. This is typical for backports, and the next sections show how to handle it. (The | head -n 3 only trims the advice text. The unchanged message and history show that no commit was made.)

Conflicts: --continue, --skip and --abort

When a cherry-pick conflicts, Git does what it does in a conflicted merge: it writes conflict markers into the file, stops, and records that a cherry-pick is in progress (.git/CHERRY_PICK_HEAD). You then have three choices:

  • Fix and continue: edit the files, git add them, run git cherry-pick --continue. Git creates the commit and reuses the original message (including the -x line, if you gave -x).
  • Skip: git cherry-pick --skip drops the current commit and moves on (matters in ranges).
  • Abort: git cherry-pick --abort returns to exactly the state before you started.

git status always tells you which situation you are in.

Bash Resolve a cherry-pick conflict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

This is the normal backport routine: pick, resolve against the old code, --continue. Read the resolved file carefully. The point of a backport is that you make the same intent work on older code, not that you reproduce the exact text of the original.

To bail out instead, run git cherry-pick --abort. Nothing is lost: your branch and files go back to how they were before the command.

Staging without committing: -n

git cherry-pick -n <commit> (long form --no-commit) applies the change to your working tree and index but does not create a commit. Use it when you want to:

  • combine several picked commits into one commit;
  • tweak the change before committing it;
  • take only part of a commit (unstage the files you do not want).
Bash Combine two picks into one commit with -n

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The two picks produced a single new commit with both files. The original authorship is not kept in that case (you are the author of the new commit), so mention the source in the message if it matters.

Picking a range

You can name several commits (git cherry-pick A B C) or a range. Remember from Revision Syntax that A..B means "everything reachable from B but not from A". It excludes A itself. So to copy the last three commits of topic, write topic~3..topic:

Terminal
git cherry-pick main..topic     # all commits on topic that main does not have
git cherry-pick A^..B           # include A: from A's parent up to B

(These two lines are illustrations and are not run.) Commits are applied oldest first, in the order of the range. If one conflicts, resolve it and run git cherry-pick --continue; Git then carries on with the remaining commits. The --abort option undoes the whole sequence, including picks that already succeeded.

Bash Cherry-pick a range of commits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Three commits were copied (two, three, four) and one.txt was not, because topic~3 is the commit that adds one, and .. excludes its left side. Off-by-one mistakes with ranges are common; always preview with git log --oneline A..B first, exactly as the example does.

Merge commits need -m

A merge commit has two parents, so "the change it made" is ambiguous: relative to which parent? Git refuses to guess:

TEXT
error: commit abc1234 is a merge but no -m option was given.

Use -m 1 to say "diff against the first parent", which is almost always what you want: it picks the mainline you merged into, so the result is "everything the merged branch contributed". Cherry-picking merges is rare and a sign to ask whether you should merge or rebase instead. See Merging Branches and Reverting Commits Safely, where -m works the same way.

Duplicates: the main pitfall

Suppose you cherry-pick a fix from feature to main, and later merge feature into main. Git sees the original commit as new work on feature and tries to apply it again. Usually that is harmless: the change is already present, so the merge finds nothing to do or applies cleanly. But when later commits touched the same lines, the second application can produce a surprising conflict, and the history shows the same change twice.

Git offers tools to see duplicate changes. They compare commits by their patch ID (a hash of the diff itself), not by commit hash:

  • git cherry -v <upstream> <head> lists commits on <head> with - if an equivalent change is already in <upstream> and + if not.
  • git log --cherry-pick --left-right A...B hides commits that exist on both sides as equivalent patches.
Bash Detect equivalent commits with git cherry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git cherry is the quickest way to answer "which of my commits are still missing from the release branch?". A minus sign means an equivalent patch is already there. Equivalence is purely textual: if the picked copy needed manual edits during a conflict, its patch ID differs and Git will report it as missing.

When to use cherry-pick, and when not

Good uses:

  • Backports: copy a fix from main to supported release branches.
  • Hotfix in the wrong place: you committed to main but the work belongs on a feature branch. Switch, cherry-pick the commit, then remove it from main (see Fixing Common Git Mistakes).
  • Rescuing one commit from an abandoned branch.
  • Mining a PR: taking a single useful commit from a branch you will not merge.

Poor uses:

  • Moving a whole branch to a new base: that is a job for rebase, which replays commits in order and drops the old ones. Cherry-picking every commit by hand gives you the same result with more typing and more mistakes.
  • Keeping two long-lived branches in sync: constant cherry-picking creates duplicates and makes git log hard to read. Merge instead.
  • Picking commits that depend on earlier ones you are leaving behind. The pick may apply with a wrong result instead of conflicting, so run the tests.

After a backport, run the tests on the target branch. A clean cherry-pick only proves that the text applied, not that the code still works with the older surroundings.

Other options worth knowing

Option What it does
-x Append "(cherry picked from commit ...)" to the message.
-n, --no-commit Apply to the working tree and index only.
-e, --edit Open the editor to change the message before committing.
-m <parent> Choose the mainline parent when picking a merge commit.
--allow-empty Keep a commit that ends up empty instead of stopping.
--keep-redundant-commits Same idea for commits whose change is already present.
--skip Drop the current commit during a sequence.
--quit Forget the sequence but keep what is already done and the files as they are.
-s, --signoff Add a "Signed-off-by" line.

When a pick results in no change because the content is already there, Git stops with a message that the previous cherry-pick is now empty. Run git cherry-pick --skip to drop it, or --allow-empty to keep it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After you cherry-pick commit F2 onto main, how does Git see the new commit compared with the original?

    A commit's hash covers its parent, tree, author and message. The copy has a different parent, so it gets a new hash. Git keeps no link between the two, which is why -x is useful.
  2. 2. You want to copy the last three commits of topic onto main. Which range is correct?

    A..B means reachable from B but not from A, so topic~3..topic gives exactly the three newest commits. The reverse order gives an empty range.
  3. 3. What does git cherry-pick -n do?

    -n (--no-commit) lets you adjust the change, combine several picks or take only part of a commit before you commit yourself.
  4. 4. A cherry-pick stops with conflicts. You decide the whole thing was a bad idea. Which command restores the state from before you started?

    --abort cancels the whole operation, including already-applied picks in a sequence, and returns the branch, index and files to the original state.
  5. 5. Why does git cherry-pick of a merge commit fail without extra options?

    The change a merge made depends on which parent you compare with. -m 1 selects the first parent, usually the branch that was merged into.

Summary

  • git cherry-pick <commit> copies the change of one commit onto your current branch as a new commit with a new hash.
  • Use -x for backports between shared branches so the origin is recorded in the message.
  • Conflicts are normal in backports: resolve, git add, then git cherry-pick --continue (or --skip / --abort).
  • -n stages the change without committing, which lets you combine or edit picks.
  • A..B excludes A; preview ranges with git log --oneline A..B first. Merge commits need -m 1.
  • Git does not remember copies, so later merges can duplicate changes; git cherry and git log --cherry-pick compare patches to find them.
  • Prefer merge or rebase for moving entire branches; use cherry-pick for single commits.

Next: Revision Syntax: Naming Commits