Rebasing Branches: Linear History with git rebase vs git merge
Rebasing Branches: Linear History with git rebase vs git merge
In team development, branches inevitably diverge. While git merge combines branches by generating a two-parent merge commit, Git provides an alternative approach called git rebase. Rebasing rewrites history to create a clean, completely linear commit timeline.
1. The Core Concept: Re-basing Your Commits
Consider two diverging branches:
If You Use git merge:
Merging creates a merge commit tying C4 and C6 together, preserving the branching knot.
If You Use git rebase:
"Rebase" literally means: take the base of my branch and change it to a new base commit! Git:
- 1Temporarily shelves commits
C5andC6as diff patches. - 2Fast-forwards
feature-searchto the tip ofmain(C4). - 3Re-applies the patches
C5andC6one by one on top ofC4as brand new commits (C5'andC6'with new hashes!).
The resulting history is completely flat and linear, as if you started developing your feature today!
2. How to Rebase in Practice
Resolving Conflicts During Rebase:
If a conflict occurs while applying C5':
- 1Git halts and displays the conflict markers in the file.
- 2Edit the file, remove the conflict markers, and stage:
git add <file>. - 3> [!IMPORTANT]
Do NOT run git commit! Instead, continue the rebase:
- 1If you want to abort the rebase and return to where you started:
3. Interactive Rebasing: Polishing Commits (git rebase -i)
Before submitting a Pull Request, you might have several messy commits:
- "wip"
- "fixed typo"
- "forgot semicolon"
- "actual feature"
Interactive rebase lets you clean, reorder, and squash them into professional commits:
Git opens an editor showing:
Common Interactive Commands:
pick: Keep the commit as is.reword: Keep the commit, but edit the commit message.edit: Pause to amend files within this commit.squash(ors): Melds this commit into the previous commit, combining messages!drop(ord): Completely deletes the commit!
4. The Golden Rule of Rebasing
main)!
Rebasing changes commit hashes. If teammates have branched off those commits, rebasing creates duplicate conflicting histories that cause chaos. Only rebase your own private local feature branches.Practice Quiz
git merge vs git rebase?squash (or s) command do inside an interactive rebase (git rebase -i)?main?Tagging Milestones and Software Releases with git tag
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.