Git Interactive Rebase: Squash, Reword, and Reorder Commits
Master git rebase -i to squash, reword, edit, reorder, and drop commits. Clean up messy commit history before merging with interactive rebase.
Detailed Explanation
Interactive Rebase with git rebase -i
Interactive rebase is one of git's most powerful features for cleaning up commit history. It lets you squash, reword, reorder, edit, and drop commits before pushing or merging.
Starting an Interactive Rebase
# Rebase the last 4 commits
git rebase -i HEAD~4
# Rebase onto main
git rebase -i main
This opens your editor with a list of commits:
pick abc1234 feat: add login form
pick def5678 fix: typo in login
pick ghi9012 feat: add validation
pick jkl3456 fix: validation edge case
Rebase Commands
Replace pick with any of these:
| Command | Short | Effect |
|---|---|---|
pick |
p |
Keep the commit as-is |
reword |
r |
Keep the commit but edit the message |
edit |
e |
Pause to amend the commit |
squash |
s |
Merge into the previous commit |
fixup |
f |
Like squash but discard the message |
drop |
d |
Remove the commit entirely |
Squashing Commits
To combine the fix commits into the feature commits:
pick abc1234 feat: add login form
fixup def5678 fix: typo in login
pick ghi9012 feat: add validation
fixup jkl3456 fix: validation edge case
This produces two clean feature commits instead of four messy ones.
Reordering Commits
Simply change the order of lines in the editor:
pick ghi9012 feat: add validation
pick abc1234 feat: add login form
Editing a Commit
Using edit pauses the rebase at that commit:
# After the rebase pauses:
# Make your changes, then:
git add .
git commit --amend
git rebase --continue
Handling Conflicts
If conflicts arise during rebase:
# Resolve conflicts in your editor, then:
git add <resolved-files>
git rebase --continue
# Or abort the entire rebase:
git rebase --abort
Use Case
Interactive rebase is essential for maintaining a clean project history. Before merging a feature branch, developers use it to squash WIP commits, fix typos in messages, and organize changes into logical units. Many teams require squash commits before merging to main, making interactive rebase a daily tool. It is also valuable during code review -- a clean history makes reviews much easier.