Interactive Rebase — Rewriting History Like a Pro
Interactive rebase (git rebase -i) is one of Git's most powerful tools. It lets you edit, reorder, squash, and drop commits before sharing your work.
Why Interactive Rebase?
Before pushing your branch, you might want to:
- Squash several small "WIP" commits into one clean commit
- Reword a commit message with a typo
- Reorder commits for a more logical history
- Drop a commit you no longer need
How It Works
git rebase -i HEAD~3
This opens an editor with your last 3 commits (oldest first):
pick a1b2c3d Add user model
pick e4f5g6h Fix typo in user model
pick i7j8k9l Add user validation
You change the action word on each line:
| Action | What it does |
|---|---|
pick | Keep the commit as-is |
reword | Keep the commit but change the message |
squash | Merge into the previous commit (combine messages) |
fixup | Merge into previous commit (discard this message) |
drop | Remove the commit entirely |
edit | Pause to amend the commit |
Common Patterns
Squashing WIP Commits
Before:
pick a1b2c3d Add login page
pick e4f5g6h WIP: fix styling
pick i7j8k9l WIP: more styling fixes
After editing:
pick a1b2c3d Add login page
fixup e4f5g6h WIP: fix styling
fixup i7j8k9l WIP: more styling fixes
Result: One clean "Add login page" commit with all the styling fixes included.
Reordering Commits
Before:
pick a1b2c3d Add tests
pick e4f5g6h Add feature
pick i7j8k9l Fix feature bug
After editing:
pick e4f5g6h Add feature
pick i7j8k9l Fix feature bug
pick a1b2c3d Add tests
The Golden Rule
Just like regular rebase: never interactive-rebase commits that have been pushed to a shared branch. It rewrites history and will cause problems for collaborators.
Try it!
In this exercise, we'll simulate the effect of interactive rebase by using amend and reset:
-
Create three commits:
echo "feature" > feature.txt && git add feature.txt && git commit -m "Add feature"echo "feature v2" > feature.txt && git add feature.txt && git commit -m "WIP fix"echo "feature v3" > feature.txt && git add feature.txt && git commit -m "WIP fix 2"
-
Now squash the last two into the first using reset:
git reset --soft HEAD~2git commit --amend -m "Add feature (complete)"
-
Verify:
git log --oneline— you should see one clean commit
When to Use Interactive Rebase
- Before opening a PR — clean up your branch's commit history
- After code review — squash fixup commits
- When commits are out of logical order — reorder them
Key Points
git rebase -ilets you edit multiple commits at once- Use
squash/fixupto combine commits - Use
rewordto fix messages - Use
dropto remove commits - Always do this before pushing to shared branches