Three-Way Merge
Part of the Version Control section of Coddy's Terminal journey — lesson 36 of 58.
If both branches have moved on independently, Git cannot just fast-forward. Instead it performs a three-way merge: it looks at the common ancestor and the two branch tips, and produces a new commit that combines them.
This new commit is the merge commit. It has two parents, one from each branch:
git switch main
git merge feature -m "Merge feature"The -m flag provides the merge commit message directly, so Git does not open an editor.
Most of the time Git can combine the changes from both branches automatically, as long as they touch different parts of the files. Conflicts only happen when both branches changed the same lines, which is the topic of the next lesson.
Challenge
MediumYou start in a fresh folder with top.txt (content: a) and bottom.txt (content: b).
Initialize the repo, make a first commit, then:
- Branch off into
featureand append the lineaddedtotop.txt; commit. - Switch to
mainand append the lineaddedtobottom.txt; commit. - Merge
featureintomainwith the messageMerge feature.
Print the count of commits reachable from HEAD using git rev-list --count HEAD. The expected count is 4 (initial + feature + main + merge).
Cheat sheet
When both branches have diverged, Git performs a three-way merge, creating a new merge commit with two parents:
git switch main
git merge feature -m "Merge feature"The -m flag sets the merge commit message without opening an editor. Git merges automatically as long as both branches changed different lines.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Version Control
2Getting Started
Initialize A RepositoryThe .git FolderConfigure Your IdentityGit StatusRecap - First Repo8Merging
What Is A MergeFast-Forward MergeThree-Way MergeMerge ConflictsResolve A ConflictRecap - Merge Master11Feature Branch Project
Project OverviewInitialize Main3Tracking Changes
The Staging AreaGit AddGit CommitModifying A Tracked FileGit LogRecap - First Commits6Recipe Site Project
Project OverviewInitialize And Ignore