Code of the Day
IntermediateGit in practice

Merge vs rebase

Two ways to combine branches, and how to choose between them.

FundamentalsIntermediate9 min read
Recommended first
By the end of this lesson you will be able to:
  • Explain what merge and rebase each do to history
  • Choose between them for a given situation
  • Apply the golden rule of rebasing

When your branch and main have both moved on, you need to combine them. Git offers two tools — and — that reach the same files but produce very different histories. Knowing the difference (and when to use each) keeps your project legible.

Merge: join the histories

git merge ties two branches together with a new merge commit that has two parents:

git switch main
git merge add-login

History keeps its true shape: it shows that add-login developed in parallel and was joined back in. Nothing is rewritten. The downside is that lots of merge commits can make history look tangled.

Rebase: replay your work on top

git rebase instead moves your branch's commits so they sit on top of the latest main, as if you'd started from there:

git switch add-login
git rebase main

The result is a straight, linear history with no merge commit — cleaner to read. But note: rebase rewrites your commits (they get new hashes), because it's replaying them onto a new base.

Choosing

  • Merge when you want to preserve exactly what happened, or when the branch is shared with others.
  • Rebase to tidy up your own, un-pushed work into a clean line before sharing it.

A common workflow: rebase your local feature branch on the latest main to stay current and linear, then merge it in when it's done.

The golden rule of rebasing: never rebase commits that other people have already pulled. Because rebase rewrites history, doing so to shared commits forces everyone else into a painful mess. Rebase private work; merge public work.

Where to go next

Both merge and rebase can hit the same snag when two changes touch the same lines: a merge conflict. Next, you'll resolve one by hand.

Finished reading? Mark it complete to track your progress.

On this page