Skip to content

Volume ITechnology

13.11.6 — Merging and Rebasing in Depth ​

You started a branch on Monday. By Friday your branch has four commits, and main has twelve new ones from other people.

You need to bring the two together. Git gives you two ways: merge and rebase. They end with the same files, but they leave different histories, and the wrong choice in the wrong place causes real trouble for a team.

Chapter 13.11.2 showed the basic merge. This page explains how Git decides what to combine, what rebase does to your commits, and how to choose.

1. How a merge decides ​

Suppose you run git merge feature while on main. Git does not compare the two branches with each other. That would not tell it who changed what.

Instead it finds the most recent commit that both branches share. That commit is the merge base. Then it asks one question for each file: what did each side change since the merge base?

ABCFDEmain (ours)feature (theirs)merge basechanges on main since Bchanges on feature since B
Git does not compare the two branches with each other. It finds their most recent common ancestor, the merge base, and asks what each side changed since then. A change made on one side only is kept. A change to the same lines on both sides is a conflict.

Three commits take part: the tip of each branch, and the merge base. That is why this is called a three-way merge. For every part of every file, the rule is:

Changed since the base on…Result
Neither sideKeep it as it is
One side onlyTake that side's change
Both sides, in different placesTake both changes
Both sides, in the same placeConflict: a human must decide

This is why merging works at all. Knowing the base lets Git see that your branch changed line 5 and mine changed line 90, and that the two do not touch.

You can ask Git for the merge base directly:

text
$ git merge-base main feature
5aa2f52cc97fb39b68e435591f27e5c08f0a611d

Fast-forward, again. If one branch has no commits of its own, then the merge base is its tip. There is nothing to combine, so Git just moves the label (Chapter 13.11.2). No merge commit exists in that case, so the branch leaves no trace in the history. That is sometimes what you want. It also loses the fact that a set of commits belonged together. git merge --no-ff forces a merge commit to keep that record.

The strategy: ort ​

When Git made a merge commit earlier, it printed Merge made by the 'ort' strategy. A merge strategy is the algorithm that combines the two sides. The default is ort, which stands for "Ostensibly Recursive's Twin". It became the default in Git 2.34 (2021), replacing an older strategy called recursive. It is a rewrite, not a different idea:

  • It is much faster, especially on big repositories and on rebases of many commits, partly because it can merge without touching your working folder.
  • It handles renames better. Remember that Git never records a rename; it works one out afterwards by comparing content (Chapter 13.11.5). One branch renaming a file while the other edits it is exactly the case that used to go wrong.
  • It has fewer odd bugs, especially around renamed folders and a file turning into a folder.

You will almost never choose a strategy yourself. Knowing what ort is answers the question when you see it in the output. The other strategies are ours (take our version of everything and merely record that the other branch was merged, which is useful to mark a branch as considered and rejected) and octopus (merge several branches at once; it refuses to handle conflicts).

Do not confuse the strategy -s ours with the option -X ours:

bash
git merge feature -X ours      # merge normally, but where there is a conflict, prefer OUR side
git merge feature -X theirs    # the same, preferring THEIR side
git merge feature -s ours      # ignore their changes completely, keep our tree

-X ours resolves only the lines that conflict, in your favour, and still takes everything else from the other branch. It is a blunt tool: it hides conflicts instead of making you look at them. Use it only when you know one side is simply right.

2. Conflict markers that show the original ​

When both sides changed the same line, you saw markers with two versions. There is a setting that adds a third part, the original from the merge base:

bash
git config --global merge.conflictstyle zdiff3

Here is the same conflict as before, with and without it. (git checkout --conflict=zdiff3 file re-creates a file's conflict in the new style.)

text
<<<<<<< ours
  return amount * 0.18;
||||||| base
  return amount * 0.2;
=======
  return amount * 0.25;
>>>>>>> theirs

The middle section, between ||||||| and =======, is the line as it was in the merge base. Now you can read the story: the rate was 0.2; our side lowered it to 0.18; their side raised it to 0.25. Without that middle part you only see two numbers and must guess who changed what. With it the correct answer is often obvious. It is a one-line setting and a real improvement, so turn it on.

rerere is a second setting worth having. The name means "reuse recorded resolution". When it is on, Git remembers how you resolved a conflict, and if the same conflict appears again it applies your answer automatically. On a long-running branch that you rebase over and over, this saves solving the identical conflict five times.

bash
git config --global rerere.enabled true

3. Rebase: replaying your commits ​

Merge joins two lines of history together. Rebase does something different: it moves your branch so it starts from a newer point.

Before (on feature) git rebase mainABCDEmainfeatureAfterABCD′E′DEmainfeatureHEAD
Rebase copies your commits on top of the new base. D′ and E′ have the same changes as D and E, but they are new commits with new ids. The old D and E are not modified; they are simply no longer on the branch.

Read the figure. Before: feature split off from B, while main moved on to C. After the rebase, your two commits D and E have been copied on top of C, and are now called D′ and E′ ("D prime"). The branch looks as if you had started your work after C all along.

The word "rebase" means exactly this: change the base the branch is built on.

text
$ git switch feature
$ git rebase main
Successfully rebased and updated refs/heads/feature.
$ git log --oneline --graph --all
* da7441d Add B
* 053db05 Add A
* 5aa2f52 Update README on main
* 3ecd169 Start the shop

A straight line, with no merge commit. Before the rebase, the two feature commits were 6cedb16 and 3b0dc3b. After it, they are 053db05 and da7441d. The ids changed. This is the most important fact about rebase.

What rebase really does ​

It cannot move a commit, because commits never change (Chapter 13.11.5). So here is what it does instead:

  1. Find the commits that are on your branch but not on the new base.
  2. Remember each one as a set of changes.
  3. Switch to the new base.
  4. Apply the changes one at a time, making a new commit for each.
  5. Move your branch label to the last new commit.

D′ has the same changes as D, but a different parent, so a different id. The old commits are not deleted. They sit untouched, and the reflog can still find them:

text
$ git reflog -5
da7441d HEAD@{0}: rebase (finish): returning to refs/heads/feature
da7441d HEAD@{1}: rebase (pick): Add B
053db05 HEAD@{2}: rebase (pick): Add A
5aa2f52 HEAD@{3}: rebase (start): checkout main
3b0dc3b HEAD@{4}: checkout: moving from main to feature

The pick lines are the commits being copied one by one. The last line is where you were before you started. If a rebase goes wrong, git reset --hard HEAD@{4} takes you back.

Conflicts during a rebase ​

Because rebase applies your commits one at a time, a conflict can happen at any step, and Git pauses there.

text
$ git rebase main
Auto-merging cart.ts
CONFLICT (content): Merge conflict in cart.ts
error: could not apply 5ac5a09... Raise tax to 25%
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".

You have three commands, and the hint tells you each one:

CommandMeaning
git rebase --continueI fixed the conflict and ran git add; carry on
git rebase --skipDrop this commit entirely and carry on
git rebase --abortCancel everything and go back to before I started

The way through is the same as for a merge: edit the file, remove the markers, git add, then git rebase --continue. If the next commit conflicts too, repeat. This is why a rebase of a long branch can mean several rounds of conflicts, where a merge would have had one.

text
$ git add cart.ts
$ git rebase --continue
Successfully rebased and updated refs/heads/rate-feature.

A trap that confuses everyone once: "ours" and "theirs" swap. Look at the markers in that conflict:

text
<<<<<<< HEAD
  return amount * 0.18;          ← this is main's version, NOT yours
=======
  return amount * 0.25;          ← this is your commit being replayed
>>>>>>> 5ac5a09 (Raise tax to 25%)

In a merge, the top half (HEAD) is your own branch. In a rebase, the top half is the branch you are rebasing onto (here, main), and the bottom half is your own commit. It feels backwards, but it follows from how rebase works: it switches to the new base first and then re-applies your work onto it, so HEAD is the base being built, and your commit is the one being brought in. If you use git restore --ours or --theirs during a rebase, remember this swap.

git pull --rebase ​

Chapter 13.11.3 showed git pull --rebase. It is fetch followed by a rebase of your local commits on top of what arrived. That is why it gives a straight line instead of a merge commit.

4. Interactive rebase: tidy up before anyone sees it ​

The most useful form of rebase lets you edit your own branch's commits before you share them.

bash
git rebase -i main          # edit every commit since the branch left main
git rebase -i HEAD~4        # edit the last four commits

Git opens your editor with one line per commit, oldest first. You change the word at the start of each line, and save.

The list Git opens in your editorpicke0bcfb3Add Dfixup5800a92fix typopickbdd0db6Add Efixupa3f08e6fix againrebaseThe resultfcb651e Add Dincludes the typo fixca53d3e Add Eincludes the second fixBoth ids are new: rebase writes new commits, as with amend.The reader sees two tidy commits and never knows about the typos.
In an interactive rebase you edit a list of commands, one per commit. fixup folds a commit into the one above it and throws away its message. Four commits become two, each doing one clear thing.
text
pick   e0bcfb3 Add D
fixup  5800a92 fix typo
pick   bdd0db6 Add E
fixup  a3f08e6 fix again

Here are the commands you can write at the start of a line:

CommandWhat it does
pickKeep the commit as it is
rewordKeep it, but let me change the message
editStop here so I can amend the commit (change files or split it)
squashFold into the commit above, and combine the two messages
fixupFold into the commit above, and discard this message
dropRemove the commit completely

You can also reorder the lines, and the commits are reordered to match.

Here is the result of the list above, using real ids:

text
$ git log --oneline -4
a3f08e6 fix again
bdd0db6 Add E
5800a92 fix typo
e0bcfb3 Add D
$ git rebase -i HEAD~4        # (after changing two lines to "fixup")
Successfully rebased and updated refs/heads/messy.
$ git log --oneline -2
ca53d3e Add E
fcb651e Add D

Four messy commits became two clean ones. A reviewer sees "Add D" and "Add E", each complete, and never sees your typos.

--autosquash: make it a habit ​

Typing fixup by hand gets old. Git can do the bookkeeping when you commit. If you notice a mistake in an earlier commit, make the fix and commit it as a fixup of that commit:

text
$ git commit --fixup HEAD~1
$ git log --oneline -3
c2478e1 fixup! Add F
9c6532f Add G
6624c70 Add F
$ git rebase -i --autosquash main
$ git log --oneline -2
da43260 Add G
7e2915b Add F

--fixup <commit> creates a commit whose message starts with fixup! and the original's name. When you later run git rebase -i --autosquash, Git puts it right under its target and already marked fixup. You just save the list. With git config --global rebase.autosquash true you do not even need the flag. Cleaning a branch before review becomes two commands.

5. Moving a branch: rebase --onto ​

Sometimes a branch was started from the wrong place. You created topic-b from topic-a, but it does not depend on topic-a and should have started from main.

Before: topic-b was started from topic-a by mistakeMa1b1maintopic-atopic-bAfter rebase --onto main topic-a topic-bMa1b1′maintopic-atopic-b
git rebase --onto main topic-a topic-b reads: "take the commits that are on topic-b but not on topic-a, and replay them onto main." It is how you move a branch to a different starting point.
text
$ git rebase --onto main topic-a topic-b
Successfully rebased and updated refs/heads/topic-b.

Read the command as a sentence: take the commits on topic-b that are not on topic-a, and replay them onto main. The three words after rebase are: where to put them (--onto main), where they currently start (topic-a), and which branch to move (topic-b).

6. The golden rule, and its real boundary ​

People say "never rebase public history". That is too broad to be useful. Here is the accurate version.

Rebase writes new commits with new ids. So anyone who already has your old commits now holds a history that disagrees with yours.

The remote, after Ana's rebase and force pushABC′origin/featureBen's laptop: still has the OLD CABCDfeatureHEAD✗ diverged
Ana rebased a branch that Ben already had, and force-pushed. The remote now has C′. Ben still has the old C, plus his own new commit D built on it. The same change exists twice under different ids, and Ben's history no longer fits the remote's.

Ana rebased a branch that Ben already had, and force-pushed. The remote now has C′. Ben has the old C and has built D on top. Git sees two histories with the "same" change under different ids, and untangling that is slow and confusing work for Ben.

So the rule depends on who has the commits:

  • Your own feature branch, before or during review: rebase freely. Nobody has built on it. After a rebase, you must replace your old copy on the remote, with git push --force-with-lease (Chapter 13.11.3 explains the lease).
  • A shared branch such as main: never. Everyone's history would diverge, and each person must repair theirs by hand.
  • A branch a colleague is also working on: agree first. Tell them before you rewrite it.

If a colleague does rebase a shared branch, git pull --rebase often copes, because it remembers where the remote branch used to be and replays only your own commits. That is the cleanest recovery.

7. Squash merge ​

A third way to bring a branch in: take everything the branch changed and write it as one commit on the target.

text
$ git switch main
$ git merge --squash messy
Squash commit -- not updating HEAD
 d.ts | 2 ++
 e.ts | 2 ++
$ git status -s
A  d.ts
A  e.ts
$ git commit -m "Add D and E (squashed)"

git merge --squash stages the combined changes and stops. You then commit them yourself, as one commit.

BeforeABDEFmainfeatureAfter git merge --squash featureABSmainS = D + E + F as one commitDEFfeaturefeature still exists, and Git still calls it "unmerged"
A squash merge takes everything the branch changed and writes it as one new commit on main. Main reads cleanly. But the branch is not recorded as merged, so Git still calls its commits unmerged.

Main stays tidy: one commit per finished piece of work. GitHub and GitLab offer this as a button called "Squash and merge".

There is one thing that surprises people. Git does not record that messy was merged, because no merge commit points at its tip. So Git still thinks the branch holds unmerged work:

text
$ git branch -d messy
error: the branch 'messy' is not fully merged.
If you are sure you want to delete it, run 'git branch -D messy'

That is not a problem, just a fact. You know the work is in, so delete it with -D.

8. Merge, rebase or squash: how to choose ​

Merge commitRebaseSquash merge
History shapeBranchy, exactOne straight lineOne commit per branch
Keeps your small commitsYesYesNo
ConflictsOncePossibly at each commitOnce
Rewrites commit idsNoYesNo
Finding a bug with bisectGoodBestCoarser

Merge keeps what truly happened, branches included. On a busy repository, the history becomes a tangle that is hard to read.

Rebase gives a straight line that reads as a list of deliberate changes. It is best for git bisect (Chapter 13.11.7), because every commit is a real state of the project. The costs: conflicts may recur at each commit, and the original shape of the work is lost.

Squash merge collapses a whole pull request into one commit. It is excellent when branches are short and each pull request is one change, which is exactly trunk-based development (Chapter 13.7). The costs are real too: a commit that touches forty files is harder to search through, and the authorship of the small commits is folded away.

The default most teams settle on: rebase your own branch onto main to keep it up to date, then squash-merge the pull request. You get a straight history, one commit per reviewed change, and no merge-commit noise.

And to stay up to date with main while working, either works:

bash
git switch feature && git merge main      # adds a merge commit to your branch
git switch feature && git rebase main     # replays your commits on the new main

Merge is safer if others share the branch. Rebase is cleaner if it is yours alone.

What the interviewer will push on ​

This is among the most common Git interview topics, so give each answer a reason, not just a command.

"What is the difference between merge and rebase?" Both bring one branch's work into another. Merge joins the two histories with a new commit that has two parents, so history shows what really happened. Rebase replays your commits on top of the other branch as new commits, so history is a straight line, but the commit ids change. The checker is whether you mention that ids change, and why that matters.

"When should you not rebase?" On any branch other people have built on. Rebase rewrites ids, so their copies diverge. The strong answer states the real boundary (your own unshared branch is fine) rather than the blanket rule.

"What does a three-way merge use?" The two branch tips and their common ancestor. Name the rule: a change on one side is kept, a change in the same place on both sides is a conflict.

"What is --force-with-lease and when do you use it?" After rebasing your own branch you must overwrite your old copy on the remote. The lease refuses if the remote has moved since you last fetched. Add that it trusts your last fetch, so you should look at what is on the remote first.

"How do you clean up a messy branch before a pull request?" git rebase -i, with fixup and squash to fold the small commits, reword for messages, and --autosquash with commit --fixup so it is routine.

"Why are 'ours' and 'theirs' reversed in a rebase?" Rebase checks out the new base first and replays your commits onto it, so HEAD is the base and your commit is the one being applied. This is a detail only people who have rebased through conflicts know.

"What is ort?" The default merge strategy since Git 2.34, a faster rewrite of recursive with better rename handling.

One thing to volunteer: say you rebase your own branch to keep it current, then squash-merge, and that you have zdiff3 and rerere on. It shows you have fixed real conflicts and made them cheaper.

Recall

  • A three-way merge compares both branch tips against their merge base: a change on one side is kept, a change to the same lines on both is a conflict. ort is the default strategy since Git 2.34: faster and better with renames. -X ours/theirs favours a side only on conflicts; -s ours discards the other side entirely.
  • Set merge.conflictstyle = zdiff3 so a conflict also shows the original line, and rerere.enabled so a conflict you solved once is solved again automatically.
  • Rebase copies your commits onto a new base, creating new commits with new ids; the old ones stay in the reflog. A rebase conflict can appear at each commit: --continue, --skip or --abort.
  • In a rebase, "ours" is the branch you are rebasing onto and "theirs" is your own commit, the opposite of a merge.
  • Interactive rebase (-i) edits your branch before sharing: pick, reword, edit, squash, fixup, drop, and reordering. commit --fixup plus --autosquash makes it routine. rebase --onto new old branch moves a branch to a different start.
  • The golden rule: rebase rewrites ids, so only rebase commits nobody else has built on. Replace your own old remote copy with --force-with-lease; never rebase a shared main.
  • Squash merge writes the whole branch as one commit, but Git does not record the branch as merged, so branch -d refuses and you use -D.
  • The common default: rebase your branch onto main, then squash-merge the pull request: straight history, one commit per reviewed change.

Self-test: What three commits does a three-way merge use? · Why does rebase change commit ids? · Which side is HEAD in a conflict during a rebase? · What does git rebase --onto main topic-a topic-b do? · Why does git branch -d refuse after a squash merge? · Who can safely be rebased, and who not?

Next: 13.11.7 covers the tools you reach for beyond the daily loop: stash for a quick shelf, cherry-pick, tags and releases, bisect to find the commit that broke something, and worktrees for working on two branches at once.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet