Appearance
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?
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 side | Keep it as it is |
| One side only | Take that side's change |
| Both sides, in different places | Take both changes |
| Both sides, in the same place | Conflict: 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
5aa2f52cc97fb39b68e435591f27e5c08f0a611dFast-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 zdiff3Here 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;
>>>>>>> theirsThe 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 true3. 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.
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 shopA 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:
- Find the commits that are on your branch but not on the new base.
- Remember each one as a set of changes.
- Switch to the new base.
- Apply the changes one at a time, making a new commit for each.
- 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 featureThe 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:
| Command | Meaning |
|---|---|
git rebase --continue | I fixed the conflict and ran git add; carry on |
git rebase --skip | Drop this commit entirely and carry on |
git rebase --abort | Cancel 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 commitsGit opens your editor with one line per commit, oldest first. You change the word at the start of each line, and save.
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 againHere are the commands you can write at the start of a line:
| Command | What it does |
|---|---|
pick | Keep the commit as it is |
reword | Keep it, but let me change the message |
edit | Stop here so I can amend the commit (change files or split it) |
squash | Fold into the commit above, and combine the two messages |
fixup | Fold into the commit above, and discard this message |
drop | Remove 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 DFour 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.
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.
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.
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 commit | Rebase | Squash merge | |
|---|---|---|---|
| History shape | Branchy, exact | One straight line | One commit per branch |
| Keeps your small commits | Yes | Yes | No |
| Conflicts | Once | Possibly at each commit | Once |
| Rewrites commit ids | No | Yes | No |
| Finding a bug with bisect | Good | Best | Coarser |
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 mainMerge 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.
ortis the default strategy since Git 2.34: faster and better with renames.-X ours/theirsfavours a side only on conflicts;-s oursdiscards the other side entirely. - Set
merge.conflictstyle = zdiff3so a conflict also shows the original line, andrerere.enabledso 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,--skipor--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 --fixupplus--autosquashmakes it routine.rebase --onto new old branchmoves 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 sharedmain. - Squash merge writes the whole branch as one commit, but Git does not record the branch as merged, so
branch -drefuses 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.