Git Rebase: Rewriting History
Merge vs Rebase
Both merge and rebase integrate changes from one branch into another, but they do it differently:
Merge: Creates a merge commit
main: A ─── B ─── C ─── M (merge commit)
\ /
feature: D ─── E
Rebase: Replays commits on top
Before rebase:
main: A ─── B ─── C
\
feature: D ─── E After rebase:
main: A ─── B ─── C
\
feature: D' ─── E'
The commits D and E are replayed on top of C, creating new commits D' and E'.
When to Use Rebase
| Use Merge When | Use Rebase When |
|---|---|
| Working on shared/public branches | Cleaning up local feature branches |
| You want to preserve exact history | You want a linear, clean history |
| Multiple people push to same branch | Only you work on the branch |
Basic Rebase
# On your feature branch
git checkout feature
git rebase mainThis replays your feature commits on top of main
Interactive Rebase
Interactive rebase (-i) lets you edit, reorder, squash, or drop commits:
git rebase -i HEAD~3 # Edit last 3 commits
This opens an editor showing:
pick abc1234 Add login form
pick def5678 Fix typo in login
pick ghi9012 Add validationCommands:
p, pick = use commit
r, reword = use commit, but edit message
s, squash = combine with previous commit
d, drop = remove commit
Common use: Squash commits
pick abc1234 Add login form
squash def5678 Fix typo in login
squash ghi9012 Add validation
This combines 3 commits into 1 clean commit.⚠️ The Golden Rule
Never rebase commits that have been pushed to a shared branch.
Rebasing rewrites history. If others have based work on the original commits, rebasing will cause conflicts and confusion.
# SAFE: Rebase your local feature branch
git checkout my-feature
git rebase mainDANGEROUS: Rebase main (shared branch)
git checkout main
git rebase feature # DON'T DO THIS!
Summary
| Command | Purpose |
|---|---|
| <code>git rebase main</code> | Replay current branch on top of main |
| <code>git rebase -i HEAD~N</code> | Interactive rebase last N commits |
| <code>squash</code> | Combine multiple commits into one |
| <code>reword</code> | Edit a commit message |