Git Merge vs Rebase
A clear explanation with examples and visualizations for Git beginners and collaborative workflows.
Quick Comparison Table
| Feature | git merge | git rebase |
|---|---|---|
| Purpose | Combine changes from one branch into another. | Reapply commits from one branch onto another base. |
| Commit History | Creates a merge commit. Keeps full branch history. | Rewrites history by moving your commits on top of another branch. No merge commit. |
| History Structure | Branching history is preserved; you can see all merges. | Linear history; looks like all commits happened sequentially. |
| Conflict Handling | Conflicts resolved during the merge commit. | Conflicts resolved per commit during the rebase. |
| Use Case | Preserve the true branch structure and context. | Clean, linear history before merging to main/master. |
| Command Example | |
|
| Effect on Remote | Safe to push; doesn’t rewrite history. | Rewriting history can cause issues if the branch is shared remotely. |
Core Idea
- Merge: Combines branches while keeping all historical branching intact.
- Rebase: Rewrites commits so your branch looks like it started from the latest commit on another branch; makes history linear and clean.
Visual Example
Scenario: `main` and `feature` branches
main: A---B---C
feature: D---E
After merge:
A---B---C------M
\ /
D-----E
M = merge commit
After rebase:
A---B---C---D'---E'
D', E' = rebased commits on top of C
Everyday Analogy
- Merge: Mixing two separate smoothies into one big smoothie. All ingredients stay.
- Rebase: Pouring your smoothie on top of the other smoothie, so it looks like you made it after theirs.
Local vs GitHub Example
Imagine:
GitHub: A — B
Local: A — C — D
After rebase:
GitHub: A — B
Local: A — B — C' — D'
Explanation:
- GitHub remains unchanged.
- Local branch now includes GitHub changes (B) and your own commits (C', D').
- History is linear, as if you started your work after the latest GitHub changes.
Summary
- Rebase does not modify GitHub; it only rewrites your local commits on top of the latest upstream commits.
- If you then push after a rebase, GitHub may require a
--forcepush because commit hashes changed. - Merge → safe, preserves all history. Rebase → clean, linear history, best for local work before pushing.