Lesson 2: The Peacekeeper (Rebase)
Merging creates a merge commit that can clutter the history. Rebase is an alternative that rewrites history to create a clean, linear timeline. It's controversial — but powerful.
Merge vs. Rebase
Merge: Preserves History (Messy but Honest)
main: A ── B ── C ────── F (merge commit)
\ /
feature: D ── E ──┘
Rebase: Rewrites History (Clean but Altered)
Before rebase:
main: A ── B ── C
feature: A ── B ── D ── E
After rebase:
main: A ── B ── C
feature: A ── B ── C ── D' ── E'
Rebase moves your branch's commits to start from the tip of main, as if you created the branch just now.
How Rebase Works
git checkout feature/login
git rebase main
Git takes each commit on feature/login and replays it on top of main. The commits get new hashes (they're technically new commits).
Interactive Rebase: git rebase -i
The most powerful feature. It lets you edit, combine, reorder, or delete commits:
git rebase -i HEAD~3 # Interactively edit the last 3 commits
This opens an editor:
pick a1b2c3d Add login form
pick e4f5g6h Fix typo in login
pick i7j8k9l Add password validation
You can change pick to:
| Command | Effect |
|---------|--------|
| pick | Keep the commit as-is |
| squash | Combine with the previous commit |
| reword | Change the commit message |
| edit | Pause to modify the commit |
| drop | Delete the commit entirely |
The Golden Rule of Rebase
⚠️ NEVER rebase commits that have been pushed to a shared branch.
Rebasing rewrites history. If others have based work on those commits, you'll create chaos. Only rebase your own local commits.
When to Use What?
| Scenario | Use | |----------|-----| | Feature branch → main | Rebase then merge (clean history) | | Shared/public branch | Merge only (preserve history) | | Cleaning up messy local commits | Interactive rebase | | Hotfix to production | Merge (clear audit trail) |
Mission Objective
Experience the clean side of Git:
- Rebase: Run
git rebase mainto replay your commits on top of main. - Admire: Run
git log --oneline --graphto see the clean linear history. - Go interactive: Try
git rebase -i HEAD~3to see the edit interface.