Git Interactive Rebase: Rewrite Commit History
Master git interactive rebase to reorder, edit, squash, drop, and reword commits. The ultimate tool for cleaning up branch history.
git rebase -i HEAD~5Detailed Explanation
What Is Interactive Rebase?
git rebase -i (interactive) opens an editor showing recent commits and lets you rewrite history by reordering, editing, squashing, dropping, or rewording commits. It is the most flexible tool for cleaning up a branch before merging.
Starting an Interactive Rebase
# Rebase the last 5 commits
git rebase -i HEAD~5
# Rebase from a specific commit
git rebase -i abc1234
The Instruction Sheet
Your editor opens with:
pick a1b2c3d Add user model
pick f4e5d6a Add user controller
pick 7g8h9i0 Fix typo
pick j1k2l3m Add user tests
pick n4o5p6q Update README
Available Commands
| Command | Short | Effect |
|---|---|---|
pick |
p |
Keep the commit as-is |
reword |
r |
Keep commit, edit message |
edit |
e |
Pause to amend the commit |
squash |
s |
Merge into previous commit, combine messages |
fixup |
f |
Merge into previous commit, discard message |
drop |
d |
Remove the commit entirely |
Example: Clean Up Before PR
pick a1b2c3d Add user model
squash f4e5d6a Add user controller
fixup 7g8h9i0 Fix typo
pick j1k2l3m Add user tests
drop n4o5p6q Update README
This combines the first three commits, keeps the test commit separate, and removes the README update.
Reordering Commits
Simply rearrange the lines in the editor. Git will replay the commits in the new order.
Handling Conflicts
If reordering or squashing causes conflicts, Git will pause and let you resolve them, then continue with git rebase --continue.
Safety
Interactive rebase rewrites commit hashes. Only use it on unpushed commits or feature branches where you are the sole contributor. If you need to update a pushed branch, use git push --force-with-lease afterward.
Use Case
Before opening a pull request, a developer uses interactive rebase to squash fix-up commits, reword unclear messages, and drop an experimental commit they no longer need.