Tour of Git
History & Undoing Changes / Lesson 3.9

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:

ActionWhat it does
pickKeep the commit as-is
rewordKeep the commit but change the message
squashMerge into the previous commit (combine messages)
fixupMerge into previous commit (discard this message)
dropRemove the commit entirely
editPause 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:

  1. 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"
  2. Now squash the last two into the first using reset:

    • git reset --soft HEAD~2
    • git commit --amend -m "Add feature (complete)"
  3. 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 -i lets you edit multiple commits at once
  • Use squash/fixup to combine commits
  • Use reword to fix messages
  • Use drop to remove commits
  • Always do this before pushing to shared branches
🎯

Goal

Squash multiple WIP commits into one clean commit using reset and amend

Terminal
$

No commits yet. Run `git init` and create your first commit.