How Git Merges

Updated · 16 min read
hardGit 2.53gitmergemerge-basemerge-treediff-algorithminternalsinterview

A three-way merge combines two versions of a file by comparing each of them with a third version: their merge base, the most recent commit that both branches started from. Every merge in Git, as well as rebase, cherry-pick and revert, is built on it. Knowing how it works explains why some changes merge cleanly and others conflict, and gives you tools to look inside a merge: git merge-base, the conflict stages in the index, git merge-tree, git log --remerge-diff and the choice of diff algorithm.

Think of two people who each photocopied a form and filled in parts of it. To combine their copies, you need the blank original. Wherever only one person wrote something, take it. Wherever both wrote different things in the same box, someone has to decide.

Syntax

Terminal
git merge-base <commit> <commit>
git merge-tree --write-tree <branch1> <branch2>
git log --remerge-diff
git diff --diff-algorithm=<algorithm>
CommandDescription
git merge-base <a> <b>It is used to print the best common ancestor of two commits.
git merge-base --all <a> <b>It is used to print every best common ancestor (more than one in a criss-cross history).
git merge-base --is-ancestor <a> <b>It is used to test whether a is an ancestor of b (exit code 0 if yes).
git ls-files -uIt is used to list the conflict stages of unmerged files during a merge.
git show :<stage>:<file>It is used to show the base (1), ours (2) or theirs (3) version of a conflicted file.
git merge-tree --write-tree <a> <b>It is used to merge two branches without touching the working folder or any branch, and report the result.
git log --remerge-diffIt is used to show what each merge commit changed compared with an automatic merge, which reveals how conflicts were resolved.
--diff-algorithm=<name>It is used to choose how diffs are computed: myers (default), minimal, patience or histogram.

The Starting Point

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
printf "%s\n" 'Term fee: $12,000' 'Exam fee: $800' 'Late fee: $250' 'Hostel fee: $9,000' 'Bus fee: $1,500' > fees.txt
git add fees.txt
git commit --quiet -m "Add the fee list"
git switch --quiet -c advitha/fees
sed -i.bak -e 's/$250/$275/' -e 's/$1,500/$1,600/' fees.txt && rm fees.txt.bak
git commit --quiet -am "Update the late and bus fees" --author="Advitha Anamaneni <advitha@example.com>"
git switch --quiet main
sed -i.bak -e 's/$250/$300/' -e 's/$12,000/$12,500/' fees.txt && rm fees.txt.bak
git commit --quiet -am "Update the term and late fees"
git log --oneline --graph --all
Output
* 1dab7ef (HEAD -> main) Update the term and late fees
| * 5f852cf (advitha/fees) Update the late and bus fees
|/
* 7ce9d7e Add the fee list

Example 1: The Merge Base

Terminal
git merge-base main advitha/fees
git log --oneline -1 "$(git merge-base main advitha/fees)"
git merge-base --is-ancestor main advitha/fees || echo "main is not an ancestor of advitha/fees"
Output
7ce9d7ede152ac20c37ab9cb52956e83122f88bf
7ce9d7e Add the fee list
main is not an ancestor of advitha/fees

Explanation: the merge base is "Add the fee list", where the two branches split. --is-ancestor returned a non-zero exit code because main has a commit that advitha/fees doesn't, so a fast-forward is impossible and a real merge is needed (see "Fast-Forward vs Merge Commit").

The Three-Way Rule

For each part of a file, Git compares the base with each side:

BaseOurs (main)Theirs (advitha/fees)ResultIn our file
AAAAExam and hostel fees: unchanged everywhere
ABAB (ours)Term fee: only main changed it
AACC (theirs)Bus fee: only Advitha changed it
ABBBBoth made the same change: no conflict
ABCConflictLate fee: both changed it differently

Without the base, Git couldn't tell "Advitha changed the bus fee" from "Navika changed the bus fee back", which is why a two-way comparison isn't enough.

Each side is compared with the merge base

Example 2: The Three Versions in the Index

Terminal
git merge advitha/fees
Output
Auto-merging fees.txt
CONFLICT (content): Merge conflict in fees.txt
Automatic merge failed; fix conflicts and then commit the result.

During a conflict, the staging area holds all three versions of the file, as numbered stages:

Terminal
git ls-files -u
git show :1:fees.txt | sed -n 3p
git show :2:fees.txt | sed -n 3p
git show :3:fees.txt | sed -n 3p
Output
100644 abdceccb37e3b6b97891eab536b0f4cdf3cb6734 1	fees.txt
100644 5609a266ce342d0a429f3a20d9a8f3ea8669b5a2 2	fees.txt
100644 9eaed8db238469fabeba31d52ee11f215cbb99f0 3	fees.txt
Late fee: $250
Late fee: $300
Late fee: $275

Explanation: git ls-files -u lists one entry per stage: 1 is the base, 2 is ours (HEAD) and 3 is theirs (the branch being merged), each with its blob ID. git show :<stage>:fees.txt prints that version; sed -n 3p picks its third line, the late fee: 250 in the base, 300 on main, 275 on Advitha's branch. The file in the working folder is Git's attempt at combining them:

Terminal
cat fees.txt
Output
Term fee: $12,500
Exam fee: $800
<<<<<<< HEAD
Late fee: $300
=======
Late fee: $275
>>>>>>> advitha/fees
Hostel fee: $9,000
Bus fee: $1,600

Explanation: the term fee (ours only) and the bus fee (theirs only) were combined automatically. Only the late fee has conflict markers. Navika settles it at $300 and commits; git add replaces the three stages with one normal entry (stage 0):

Terminal
sed -i.bak -e "/^<<<<<<< /d" -e "/^=======/d" -e "/^>>>>>>> /d" -e '/$275/d' fees.txt && rm fees.txt.bak
git add fees.txt
git ls-files -s fees.txt
git commit --quiet --no-edit
Output
100644 7ae777e369c50a23fcdf59de10aa239f3e8839a9 0	fees.txt

Example 3: How Was a Merge Resolved?

git show on a merge commit normally shows only lines that differ from both parents (a "combined diff"), which hides most of what happened. --remerge-diff instead redoes the automatic merge and shows how the commit differs from it, which is exactly how the conflicts were resolved:

Terminal
git log -1 --remerge-diff --format="%s"
Output
Merge branch 'advitha/fees'
 
diff --git a/fees.txt b/fees.txt
remerge CONFLICT (content): Merge conflict in fees.txt
index ea227b6..7ae777e 100644
--- a/fees.txt
+++ b/fees.txt
@@ -1,9 +1,5 @@
 Term fee: $12,500
 Exam fee: $800
-<<<<<<< 1dab7ef (Update the term and late fees)
 Late fee: $300
-=======
-Late fee: $275
->>>>>>> 5f852cf (Update the late and bus fees)
 Hostel fee: $9,000
 Bus fee: $1,600

Explanation: the diff compares "the automatic merge, with conflict markers" with "the commit". The markers and Advitha's 275 were removed, keeping 300. A merge commit with no manual changes shows no diff at all here. This is the best way to review a merge in a pull request or to find a bad conflict resolution later. Two other views:

Terminal
git show --stat --format="%s" --diff-merges=first-parent HEAD
Output
Merge branch 'advitha/fees'
 
 fees.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

--diff-merges=first-parent (or -m --first-parent) shows the merge's changes against its first parent: everything the merge brought into main, here only the bus fee.

Example 4: Merging Without Touching Anything

git merge-tree --write-tree performs a full merge in memory and reports the result, without changing the working folder, the index or any branch. It is used by servers to check whether a pull request can be merged, and by scripts to test a merge before doing it:

Terminal
git switch --quiet -c srihitha/fees "main^{/Add the fee list}"
sed -i.bak 's/$9,000/$9,500/' fees.txt && rm fees.txt.bak
git commit --quiet -am "Raise the hostel fee" --author="Srihitha Anamaneni <srihitha@example.com>"
sed -i.bak 's/$12,000/$13,000/' fees.txt && rm fees.txt.bak
git commit --quiet -am "Raise the term fee" --author="Srihitha Anamaneni <srihitha@example.com>"
git switch --quiet main
git merge-tree --write-tree --name-only main srihitha/fees; echo "exit code: $?"
Output
624c276f232bfe3325ea9ea01a9bd2c7dd32c94d
fees.txt
 
Auto-merging fees.txt
CONFLICT (content): Merge conflict in fees.txt
exit code: 1

Explanation: the output starts with the ID of the tree the merge would produce (with conflict markers inside), then the conflicted file names (--name-only), then the messages a real merge would print. Exit code 1 means there are conflicts: Srihitha's term fee clashes with Navika's. Nothing else changed: main, the index and fees.txt are exactly as before, and no merge is in progress. With exit code 0, the printed tree is the clean merge result, ready for git commit-tree (see "Build a Commit by Hand").

Example 5: Criss-Cross Merges

When two branches merge each other back and forth, they can end up with two equally good merge bases:

Terminal
git init --quiet ../criss-cross
cd ../criss-cross
echo 'Term fee: $12,000' > fees.txt
git add fees.txt
git commit --quiet -m "Start"
git branch other
echo 'Late fee: $250' > late.txt
git add late.txt
git commit --quiet -m "Main: add the late fee"
git switch --quiet other
echo 'Bus fee: $1,500' > bus.txt
git add bus.txt
git commit --quiet -m "Other: add the bus fee"
git merge --quiet main -m "Other: merge main"
git switch --quiet main
git merge --quiet "other~1" -m "Main: merge other's first commit"
git merge-base --all main other
git log --oneline --graph --all
Output
b0cb58fc2e7b7e86dd3e512353aee72cbbb996d5
760d219efa56f888f86668a0a21e6aac5e25f00c
*   6e8a3a9 (HEAD -> main) Main: merge other's first commit
|\
| | * c3c6a08 (other) Other: merge main
| |/|
| |/
|/|
* | 760d219 Main: add the late fee
| * b0cb58f Other: add the bus fee
|/
* 2c21d7e Start

Explanation: other merged main (with "add the late fee"), and main merged other's first commit ("add the bus fee"), so each branch now contains both of those commits, and neither commit is newer than the other. git merge-base --all prints both: there is no single best common ancestor. When these branches are merged next, ort first merges the two bases into a temporary virtual merge base and uses that as the base for the real merge. This is the "recursive" idea behind the old strategy's name, and why it rarely produces surprising conflicts.

Diff Algorithms

A merge is built from diffs, and Git has four ways of computing them. On most changes, they give the same result. On code where many lines look alike, such as lines with only { or }, they can differ a lot. Navika replaces a function and adds another:

Terminal
cd ../fee-tracker
cat > Fees.java <<'EOF'
void printFees(int fee)
{
    for (int i = 0; i < 3; i++)
    {
        print("Term fee: ");
        print(fee);
    }
}
 
int total(int n)
{
    if (n > 1)
    {
        return total(n - 1) + n;
    }
    return 1;
}
 
void main()
{
    printFees(total(10));
}
EOF
git add Fees.java
git commit --quiet -m "Add Fees.java"
cat > Fees.java <<'EOF'
int lateFee(int days)
{
    if (days > 10)
    {
        return 250;
    }
    return 0;
}
 
void printFees(int fee)
{
    for (int i = 0; i < 3; i++)
    {
        print("Term fee: ");
        print(fee);
    }
}
 
void main()
{
    printFees(lateFee(12));
}
EOF
git diff --diff-algorithm=myers | tail -n +5
Output
@@ -1,22 +1,22 @@
-void printFees(int fee)
+int lateFee(int days)
 {
-    for (int i = 0; i < 3; i++)
+    if (days > 10)
     {
-        print("Term fee: ");
-        print(fee);
+        return 250;
     }
+    return 0;
 }
 
-int total(int n)
+void printFees(int fee)
 {
-    if (n > 1)
+    for (int i = 0; i < 3; i++)
     {
-        return total(n - 1) + n;
+        print("Term fee: ");
+        print(fee);
     }
-    return 1;
 }
 
 void main()
 {
-    printFees(total(10));
+    printFees(lateFee(12));
 }

Explanation: the default myers algorithm found the smallest number of changed lines by matching up the {, } and blank lines, which mixes the old and new functions together. The diff is correct, but hard to read: printFees didn't really change. The histogram algorithm looks for lines that appear rarely first, such as void printFees(int fee), and lines up around them:

Terminal
git diff --diff-algorithm=histogram | tail -n +5
git commit --quiet -am "Replace total with lateFee"
Output
@@ -1,3 +1,12 @@
+int lateFee(int days)
+{
+    if (days > 10)
+    {
+        return 250;
+    }
+    return 0;
+}
+
 void printFees(int fee)
 {
     for (int i = 0; i < 3; i++)
@@ -7,16 +16,7 @@ void printFees(int fee)
     }
 }
 
-int total(int n)
-{
-    if (n > 1)
-    {
-        return total(n - 1) + n;
-    }
-    return 1;
-}
-
 void main()
 {
-    printFees(total(10));
+    printFees(lateFee(12));
 }

Explanation: now the diff says what really happened: a new function lateFee was added at the top, total was removed, and one line in main() changed. printFees is untouched.

AlgorithmHow it worksWhen to choose it
myersThe classic shortest diff, with some tidying heuristicsThe default; fine for most changes
minimalMyers, working harder to find the very smallest diffRarely needed; slower
patienceMatches lines that appear exactly once in both versions firstCode with many look-alike lines
histogramAn improved, faster patience that also handles lines that appear a few timesA good choice for everyone: git config --global diff.algorithm histogram

Common Mistakes

Reading a merge commit with plain git show. The combined diff hides most of the merge. Use --remerge-diff to see conflict resolutions, or --diff-merges=first-parent to see what the merge brought in.

Thinking Git merges by comparing the two tips only. Git always uses the merge base. A change "back to the original" on one side is a change too.

Making a test merge in your working folder to see if it conflicts. git merge-tree --write-tree answers that without touching anything.

Blaming the merge for an ugly diff. Try --diff-algorithm=histogram; the change may be simpler than it looks.

Under the Hood

git merge first runs the equivalent of git merge-base --all on HEAD and the branch. With one base, ort reads the three trees (base, ours, theirs) and walks them together, path by path. For a path that changed on only one side, it takes that side's version without looking inside. For a path changed on both sides, it detects renames, then runs a line-level three-way merge on the contents (the xdiff library's merge, using the chosen diff algorithm). Clean results become stage 0 entries; conflicting paths get stages 1, 2 and 3 in the index and a file with markers in the working folder. With several bases, ort first merges the bases with each other, recursively, into a virtual commit that exists only in memory. Because ort builds the whole result in memory first, git merge-tree --write-tree can run the exact same code and just write the resulting tree as an object, without updating anything else.

Interview Corner

What is a merge base?

The best common ancestor of two commits: the most recent commit both branches contain. git merge-base a b prints it. A three-way merge compares each side with it.

Why does Git use a three-way merge instead of comparing the two branches?

With only two versions, Git can't tell which side made a change. With the base, it knows: a part changed on one side only is taken, and a part changed differently on both sides is a conflict.

What are the stages in the index during a conflict?

Stage 1 is the base version, stage 2 ours, stage 3 theirs. git ls-files -u lists them, and git show :2:<file> prints one. git add replaces them with a single stage 0 entry.

How can you tell whether two branches would conflict without merging?

git merge-tree --write-tree a b. It merges in memory, prints the result tree and any conflicts, and exits with code 1 if there are conflicts, without touching the working folder or branches.

Practice

Challenge: a clean trial merge. Create a branch advitha/books from "Add the fee list" that adds a file books.txt, then test-merge it into main with git merge-tree --write-tree and print the exit code. Finally, confirm that main still has no books.txt.

What does Git print? Before you open the solution, decide how many lines merge-tree prints and the exit code.

Show solution
Terminal
git switch --quiet -c advitha/books "main^{/Add the fee list}"
echo 'Books fee: $600' > books.txt
git add books.txt
git commit --quiet -m "Add the books fee" --author="Advitha Anamaneni <advitha@example.com>"
git switch --quiet main
git merge-tree --write-tree main advitha/books; echo "exit code: $?"
ls books.txt 2>/dev/null || echo "main has no books.txt"
Output
1d844d6b10331d235c41d7ad63ee2cb453319b44
exit code: 0
main has no books.txt

One line, the ID of the merged tree, and exit code 0: the merge is clean, because the branch only added a new file. main is unchanged. To make the merge for real, run git merge advitha/books, or build the commit from that tree with git commit-tree.

Checkpoint. In a practice repository, create a conflict, and during it inspect git ls-files -u and the three stages with git show :1:<file>, :2: and :3:. After resolving and committing, view the resolution with git log -1 --remerge-diff.

Quick check: how Git merges

4 questions
1What does git merge-base main feature print?
2In a three-way merge, a line changed only on the other branch. What happens?
3During a conflict, which stage holds "theirs"?
4Which command shows how the conflicts in a merge commit were resolved?

Key Takeaways

Quick reference

CommandIt is used to
git merge-base <a> <b>Find the common ancestor
git merge-base --all <a> <b>Find all best common ancestors
git ls-files -uList conflict stages
git show :2:<file>Show our version during a conflict
git merge-tree --write-tree <a> <b>Test a merge without side effects
git log --remerge-diffShow conflict resolutions in merges
git config --global diff.algorithm histogramUse the histogram diff

Was this tutorial helpful?

Lesson 97 of 106