git merge — Combining Work
The git merge command integrates changes from one branch into another. It's how you bring feature work back into main.
How Merge Works
When you run git merge feature while on main:
- Git finds the common ancestor of both branches
- It combines the changes from both sides
- It creates a new merge commit with two parents
main: A --- B --- C ------- M
\ /
feature: D --- E ----
The merge commit M has two parents: C (from main) and E (from feature).
Fast-Forward Merge
If main hasn't moved since the branch was created, Git can just move the pointer forward — no merge commit needed:
Before: main → A --- B feature → C --- D
After: main → A --- B --- C --- D ← feature
Try it!
Build a feature branch and merge it:
- Create a commit on main:
echo "base" > base.txtthengit add base.txtthengit commit -m "Add base" - Create and switch to feature:
git checkout -b feature - Add a feature commit:
echo "feature" > feature.txtthengit add feature.txtthengit commit -m "Add feature" - Switch back to main:
git checkout main - Merge:
git merge feature
Watch the graph — you should see the merge commit connecting both lines of history.
After Merging
Once merged, the feature branch is no longer needed. Clean up with:
git branch -d feature
The commits from the branch are preserved in main's history through the merge commit.