1. Home
  2. Blog
  3. DevOps

DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick copies the changes from one commit onto your current branch without merging everything else. Learn when to use it, the options that keep history traceable, and how to handle conflicts, with every command run in a real repository.

9 min read
Git cherry-pick explained: copy the commit you need, safely, tested

Key takeaways

  • Git cherry-pick applies one commit’s changes to the current branch as a new commit with a new hash.
  • Use -x to record where the commit came from, which makes hotfix history traceable.
  • A range A..B excludes A. Use A^..B to include it.
  • On a conflict, fix and run --continue, or back out completely with --abort.

A bug fix lands on your development branch, but the release branch that customers run needs it today, without the half-finished features sitting next to it. Merging would bring everything. Git cherry-pick lets you take just the fix: it reads the change one commit introduced and applies it on top of your current branch.

We built a small repository and ran every command below with Git 2.56.0 on Windows, using a demo author name and email. Hashes and outputs are copied from that run, so yours will differ. If commits and branches are new to you, start with our Git tutorial for beginners.

What does git cherry-pick do?

Every commit records a snapshot plus a pointer to its parent. Cherry-pick takes the difference between a commit and its parent, applies that difference to your current branch, and creates a new commit with the same message and author. The original commit stays where it was. Nothing is moved; the change is copied.

The scenario

We created an initial commit, branched release-1.0 from it, and then made three commits on a feature branch:

$ git log --oneline feature
201c2ee New UI banner
48ea901 Fix divide-by-zero crash
4335edf Add discount feature
4efe08e Initial release

The release branch needs only 48ea901, the crash fix. The discount feature and new UI are not ready for customers.

A basic cherry-pick

$ git switch release-1.0
$ git cherry-pick 48ea901
[release-1.0 8380813] Fix divide-by-zero crash

$ git log --oneline
8380813 Fix divide-by-zero crash
4efe08e Initial release

$ ls
VERSION  app.py  util.py

The release branch now has the fix, including the new util.py, and none of the feature files: no discount.py and no ui.py. That is the whole point. Run your tests on the release branch afterwards, because a fix written against newer code may depend on something the old branch lacks.

New hash, same change

The copy got hash 8380813, while the original is 48ea901. A commit hash covers its parent and timestamps, and the copy has a different parent, so the hash must differ. Git can still tell the two commits carry the same change by comparing their patch-id, a hash of the diff itself:

$ git show 48ea901 | git patch-id --stable
dd5f4e371770...
$ git show HEAD | git patch-id --stable
dd5f4e371770...

Identical patch-ids, different commit hashes. Remember this when someone asks “is the fix on release?”: searching for the original hash will not find it.

Checking what is missing with git cherry

$ git cherry -v release-1.0 feature
+ 4335edf... Add discount feature
- 48ea901... Fix divide-by-zero crash
+ 201c2ee... New UI banner

git cherry uses patch-ids to compare branches. A minus sign means an equivalent change already exists on release-1.0; a plus means it does not. That gives you a quick audit of which fixes still need picking.

Recording the source with -x

$ git cherry-pick -x 48ea901
$ git log -1 --format=%B
Fix divide-by-zero crash

(cherry picked from commit 48ea901313c32455d8ce259ba032b311a4740bb5)

-x appends the original full hash to the message. When you maintain several release lines, this line is how you trace a fix back to its source months later. Many teams make it mandatory for hotfixes. Use it when the original commit is on a shared branch; skip it when picking from a private branch that will be deleted, because the reference would point nowhere.

Applying without committing: -n

$ git cherry-pick -n 48ea901
$ git status --short
M  app.py
A  util.py
$ git log --oneline -1
4efe08e Initial release

-n (or --no-commit) applied and staged the changes but created no commit. Use it to combine several picked commits into one, or to adjust the change before committing.

Tip: before any cherry-pick, check git status. Starting with uncommitted changes makes conflicts much harder to untangle.

Picking a range of commits

$ git cherry-pick 4335edf..feature
$ git log --oneline
60dd132 New UI banner
14c152c Fix divide-by-zero crash
4efe08e Initial release

We asked for 4335edf..feature and got two commits, not three. As in git log, A..B means “commits reachable from B but not from A”, so A itself is excluded. To include A, write 4335edf^..feature. Commits are applied oldest first, which keeps dependent changes in order. This range behaviour also catches people with revert, as our git reset vs revert guide shows.

Handling conflicts

We changed price = 100 to 120 on the release branch, and to 99 in a feature commit called “Promo price”, then tried to pick the promo:

$ git cherry-pick 18fa62a
hint: run "git cherry-pick --abort".
$ git status --short
UU app.py
$ head -5 app.py
<<<<<<< HEAD
price = 120
tax = 0.18
=======
price = 99

Both branches edited the same line, so Git stopped and marked the conflict. You now have three choices:

  • Resolve: edit the file, git add app.py, then git cherry-pick --continue.
  • Abort: git cherry-pick --abort returns the branch to exactly where it was. After aborting, our file showed price = 120 again.
  • Skip: in a range, --skip drops this commit and continues with the next.

Conflicts during cherry-pick are often a warning sign: the commit depends on changes the target branch does not have. Ask whether you really want this commit there.

Empty picks and –skip

We picked the fix onto a branch that already had it:

$ git cherry-pick 48ea901
The previous cherry-pick is now empty, possibly due to conflict resolution.
$ git cherry-pick --skip

Git noticed the change was already present and refused to make an empty commit. --skip moves on. This happens often when someone has already picked a fix and you do not know it, which is another reason to run git cherry first.

What happens when you merge later?

Cherry-picking leaves the same change in history twice. We merged the feature branch (up to the UI commit) into a branch that already held the picked fix:

*   b25922e Merge commit '201c2ee' into empty-demo
|\
| * 201c2ee New UI banner
| * 48ea901 Fix divide-by-zero crash
| * 4335edf Add discount feature
* | cf37c06 Fix divide-by-zero crash
|/
* 4efe08e Initial release

The merge was clean, because both sides made the identical change, and util.py contained the function once. But the log now shows the fix twice under two hashes. When we also merged a later commit that changed the neighbouring price line, Git reported a conflict, because changes on adjacent lines can collide. Duplicate history is harmless in small doses, but heavy cherry-picking between long-lived branches makes merges and history harder to follow. Our merge vs rebase guide covers the alternatives.

When to cherry-pick, and when not to

Good use Better alternative
Hotfix to a release or maintenance branch —
Rescue one commit from an abandoned branch —
Backport a security fix to older versions —
Moving most of a feature branch Merge or rebase the branch
Shipping unfinished work hidden from users Feature flags
Undoing a commit git revert

A common team rule is “fix on the main branch first, then cherry-pick to release”, so the fix is never lost in the next release. Tag the patched release using semantic versioning, for example 1.0.1, and let your CI/CD pipeline run the full test suite on it.

A safe cherry-pick checklist

  1. Run git status and start from a clean working tree.
  2. Run git cherry -v target source to see whether the change is already there.
  3. Pick with -x when the source commit lives on a shared branch.
  4. For several commits, check whether your range should start at A or A^.
  5. If a conflict looks large, --abort and ask whether a missing earlier commit is needed first.
  6. Run the tests on the target branch before pushing.

Final thoughts

Git cherry-pick is a precise tool for copying one change to another branch. Use -x for traceability, remember that ranges exclude their first commit, check git cherry before picking, and reach for --abort without fear. Keep it for hotfixes and rescues; for moving whole features, merging stays simpler.

Frequently asked questions

What does git cherry-pick do?

It takes the changes from a chosen commit and applies them to your current branch as a new commit with a new hash. The original commit and branch are not changed.

How do I cherry-pick multiple commits?

List the hashes, or use a range such as A..B. The range excludes A, so use A^..B to include it. Git applies the commits from oldest to newest.

How do I undo or stop a cherry-pick?

During a conflict, run git cherry-pick –abort to return to the previous state. If the pick already finished, use git revert on the new commit, or reset if it was never pushed.

What does git cherry-pick -x do?

It adds a line to the commit message naming the original commit hash, such as cherry picked from commit 48ea901. This keeps backported fixes traceable.

Is cherry-picking bad practice?

No, it is ideal for hotfixes and backports. Heavy use between long-lived branches duplicates history and can complicate later merges, so prefer merging for whole features.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →