Merge, rebase and cherry-pick in Git
Every team that uses branches has to answer the same question many times a day: how do the commits on one branch get onto another? Git gives you three tools. git merge joins two histories with a merge commit. git rebase replays your commits on top of another branch so the history reads as a straight line. git cherry-pick copies one or a few chosen commits without bringing the rest of the branch. They all apply the same changes; what differs is the history they leave behind and who else is affected by it.
The examples follow one invented repository, OrdersPortal, with a main branch, a feature/discounts branch and a release/2.4 maintenance branch. Every command block that shows output was run with Git 2.43 in a throwaway repository; commit hashes on your machine will differ.
Topics on this page
Section titled “Topics on this page”| Topic | Use it when |
|---|---|
| Merge | You want to integrate a branch and keep a record of when it joined. |
| Rebase | You want your local branch to sit on top of the latest main with a linear history. |
| Interactive rebase | You want to squash, reword or reorder your own commits before review. |
| Force pushing safely | You rewrote commits that you had already pushed. |
| Cherry-pick | You need one specific commit on another branch, such as a fix for a release branch. |
| Choosing between them | You are setting a team convention. |
git merge integrates another branch into the branch you are on. If your branch has not moved since the other branch started, Git can simply move the pointer forward (a fast-forward). If both branches have new commits, Git creates a merge commit with two parents. --no-ff forces a merge commit even when a fast-forward is possible, which keeps a visible “this feature landed here” marker; the default Merge pull request option on GitHub uses the same --no-ff behavior.
Merging never changes existing commits, so it is always safe on shared branches. The cost is noise: on a busy repository the graph fills with merge commits, and git log without --first-parent interleaves commits from many features.
git switch maingit merge --no-ff -m "Merge branch 'feature/discounts'" feature/discountsgit log --oneline --graphOutput:
* af7aa4b Merge branch 'feature/discounts'|\| * d842450 Apply discount to subtotal| * 2de3f96 Add discount codes* | 571315e Add VAT calculation|/* 9e701a8 Add order status* a8abe37 Add order pricingPitfalls:
- A merge in progress blocks other work. If a merge stops on conflicts, either resolve them,
git addthe files and rungit commit, or rungit merge --abortto return to where you started. - Reading history needs the right view. Use
git log --first-parent mainto see one line per merged feature instead of every commit inside it.
Rebase
Section titled “Rebase”git rebase main, run on a feature branch, takes the commits that are on your branch but not on main, sets them aside, moves the branch to the tip of main, and replays the commits one at a time. Each replayed commit has the same change and message but a new parent, so it gets a new hash. The result is a history that reads as if you had started the feature after the latest main commit.
That linear history makes git log, git bisect and git blame easier to follow, and a rebased branch can then be merged with a fast-forward. The price is that rebase rewrites commits. That leads to the golden rule of rebasing: do not rebase commits that other people have based work on. Rebasing your own unpushed feature branch is always fine. Rebasing a branch you pushed but nobody else uses is fine if you force push carefully. Rebasing main, develop or a branch teammates have pulled creates duplicate commits and painful conflicts for everyone else.
git switch feature/discountsgit rebase maingit log --oneline --graphOutput (the two feature commits now sit on top of Add VAT calculation, with new hashes):
* 4b03a8d Apply discount to subtotal* 40dba22 Add discount codes* 571315e Add VAT calculation* 9e701a8 Add order status* a8abe37 Add order pricingPitfalls:
- Conflicts can repeat per commit. Rebase replays commits one by one, so a conflict in a file touched by five commits may need resolving more than once. Resolve,
git add, thengit rebase --continue;git rebase --abortrestores the branch. Enablingrerere.enabledlets Git remember resolutions. - Pulling with rebase is a choice.
git pull --rebase(orpull.rebase=true) rebases your local commits onto what you fetched instead of creating “Merge branch ‘main’ of …” commits. Agree on one setting per team.
Interactive rebase
Section titled “Interactive rebase”git rebase -i <base> opens a todo list of your commits before replaying them. Each line starts with a command: pick keeps the commit, reword edits its message, edit stops so you can amend it, squash folds it into the previous commit and combines the messages, fixup folds it in and discards its message, and drop removes it. Reordering the lines reorders the commits. Use it to turn “WIP”, “fix typo” and “address review” commits into a few meaningful ones before a pull request is reviewed or merged.
A faster habit is to create fixup commits as you go and let Git place them. git commit --fixup=<commit> writes a commit titled fixup! <original subject>, and git rebase -i --autosquash moves it under its target and marks it fixup. In the run below the editor step is skipped (GIT_SEQUENCE_EDITOR=true) to show the result.
git log --onelineGIT_SEQUENCE_EDITOR=true git rebase -i --autosquash maingit log --onelineOutput:
c64ccff fixup! Add carrier label230bf2e Add carrier label0df0f31 Free shipping over 50e3afb7e Add flat shipping4d2f0f9 Add carrier label0df0f31 Free shipping over 50e3afb7e Add flat shippingThe first four lines are before the rebase; after it, the fixup is folded into Add carrier label.
Pitfalls:
- Only rewrite your own commits. The golden rule applies: interactive rebase of shared commits causes the same problems as any rebase.
- Squash on merge may make this unnecessary. If the team uses squash merges for pull requests, the commit list inside the branch matters less; tidy it only when reviewers read commit by commit.
Force pushing safely
Section titled “Force pushing safely”After you rebase or amend commits you had already pushed, the remote branch and your local branch have diverged and a normal push is rejected. git push --force overwrites the remote branch unconditionally, which silently deletes any commits a teammate pushed in the meantime. git push --force-with-lease overwrites only if the remote branch still points where your last fetch saw it; if someone pushed since, the push fails and you can fetch and look first. Since Git 2.30, adding --force-if-includes also checks that you have actually integrated the remote commits you fetched, which closes the gap left by background fetches in some editors.
git push --force-with-lease --force-if-includes origin feature/discountsPitfalls:
- Protected branches reject force pushes. The Block force pushes rule in GitHub rulesets is on by default, and GitLab protected branches allow force pushes only when Allowed to force push is turned on. That is a feature, not a bug.
- A lease is only as fresh as your last fetch. Running
git fetchand then force pushing without looking defeats the check; inspectgit log origin/feature/discountsfirst.
Cherry-pick
Section titled “Cherry-pick”git cherry-pick <commit> applies the change introduced by one existing commit on top of your current branch and creates a new commit with the same message and a different hash. You can pass several commits, or a range A..B, which means “the commits after A up to and including B”. The classic use is a backport: a bug is fixed on main, and the same fix must ship in a patch release from release/2.4 without bringing along the unreleased features that followed it on main. Other uses are moving a commit that landed on the wrong branch, and taking one urgent fix from a teammate’s long-running branch.
Use -x on public backports: it appends (cherry picked from commit <hash>) to the message, so anyone can trace the copy to its source. -n (--no-commit) applies the change without committing so you can combine several picks into one commit. To cherry-pick a merge commit you must name the parent to diff against with -m 1.
git switch release/2.4git cherry-pick -x d326398git log -1 --format='%h %s%n%n%b'git cherry -v release/2.4 mainOutput:
[release/2.4 a1e8a7e] Fix rounding of order totals 1 file changed, 1 insertion(+), 1 deletion(-)a1e8a7e Fix rounding of order totals
(cherry picked from commit d32639897634ab2bd7e209133457fabc6b44dfd1)
- d32639897634ab2bd7e209133457fabc6b44dfd1 Fix rounding of order totals+ 65a6a588b94879c9c8429f7c8f6c5b8b6ad6ce92 Add CSV exportgit cherry compares by patch content: - means an equivalent change is already on release/2.4, + means it is not. git log --cherry-mark --oneline release/2.4...main gives the same answer with = and + markers.
When the target branch has changed the same lines, the pick stops with a conflict, exactly like a merge:
CONFLICT (content): Merge conflict in shipping.txterror: could not apply 0df0f31... Free shipping over 50hint: After resolving the conflicts, mark them withhint: "git add/rm <pathspec>", then runhint: "git cherry-pick --continue".Resolve the file and run git cherry-pick --continue, skip that commit with --skip, or undo the whole operation with --abort.
Pitfalls:
- Duplicates come back at merge time. A cherry-picked commit and its original are different commits. If both branches are later merged, Git usually notices the identical change, but if the code moved in between you get confusing conflicts. Cherry-pick into branches that will not be merged back (release branches), or merge instead.
- Many picks mean the wrong tool. If you need most of a branch, merge or rebase it; ten cherry-picks lose the branch’s context and multiply conflicts.
- The fix may depend on earlier commits. A pick applies only the diff of that commit. If it relies on a helper added earlier on
main, the release branch will not compile; check with the project’s tests before pushing.
Choosing between them
Section titled “Choosing between them”| Situation | Recommendation |
|---|---|
Bring the latest main into your private feature branch |
git rebase main (or git pull --rebase) |
Integrate a reviewed pull request into main |
The platform’s merge button: merge commit, squash or rebase, per team policy |
| Integrate a long-running branch that others share | git merge |
| Ship one fix to a release branch | git cherry-pick -x |
| Clean up “WIP” commits before review | git rebase -i with --autosquash |
| A branch others have pulled | Never rebase it; merge |
GitHub and GitLab both offer three pull or merge request strategies: a merge commit, squash and merge (all commits become one), and a rebase-style merge that replays commits without a merge commit (GitHub’s Rebase and merge, GitLab’s fast-forward merge method). Pick one default per repository so history looks the same everywhere.
Interview questions
Section titled “Interview questions”What is the difference between merge and rebase? Both integrate changes. Merge creates a merge commit with two parents and leaves existing commits untouched. Rebase replays your commits on a new base, creating new commits with new hashes and a linear history. Merge is safe on shared branches; rebase is for commits only you have.
What is the golden rule of rebasing and why does it exist? Do not rebase commits other people have based work on. Rebase replaces commits with new ones; anyone who built on the old ones now has a diverged history and will reintroduce duplicates or fight conflicts when they pull.
Why prefer --force-with-lease over --force?
--force overwrites the remote branch regardless of what is there. --force-with-lease refuses if the remote moved since your last fetch, so you cannot silently delete a teammate’s commits. --force-if-includes adds a check that you integrated what you fetched.
When is cherry-pick the right tool, and what does -x add?
For a few specific commits that must exist on a branch that will not be merged with the source, typically backporting a fix to a release branch. -x records the source commit hash in the message for traceability.
Senior scenario: a critical payment fix is merged to main, but main also contains two unreleased features. Production runs release/2.4. How do you ship the fix?
Create a short-lived branch from release/2.4, git cherry-pick -x the fix commit (and any small prerequisite it depends on), run the full test suite, and merge that branch into release/2.4 through the normal review and CI path. Tag the patch release from release/2.4. Do not merge main into the release branch, because that ships the unreleased features. Afterwards confirm with git cherry that nothing else is missing, and make sure the fix is on every supported release line.
Related pages
Section titled “Related pages”- Git fundamentals: the commands and concepts these operations build on.
- Branching strategies: GitHub Flow, Git Flow and trunk-based development.
- Undo, stash and recover work: reset, revert, reflog and stash.
- Tags, hooks and commit conventions: tagging the patch release you just cherry-picked.
- Git cheatsheet