Interactive Rebase

Interactive Rebase

Interactive rebase is Git's "Swiss Army Knife" for cleaning up your local history. It allows you to edit, squash, reorder, and delete commits before you share them with the rest of your team.


1. Starting an Interactive Rebase

To start an interactive rebase, use the -i flag followed by the point in history you want to modify. To look at your last 4 commits:

git rebase -i HEAD~4

Original HistoryWIP 1Typo fixWIP 2After Interactive RebaseOne Clean Commit


2. The "Todo List" Commands

When you run the command, Git opens a temporary file listing your commits in chronological order (oldest at the top). You change the action word at the start of each line:

CommandShortcutDescription
pickpUse the commit as is.
rewordrUse the commit, but edit the commit message.
editeStop for amending (allows you to change files).
squashsMeld into the previous commit; keep both messages.
fixupfMeld into the previous commit; discard this message.
dropdRemove the commit entirely.

3. Practical Example: Squashing WIPs

If your history looks like this:

pick a1b2c3d Add feature login
pick d4e5f6g WIP: styling
pick h7i8j9k fix typo in css
pick l1m2n3o WIP: validation

You can "squash" the messy parts into the main feature commit by changing it to:

pick a1b2c3d Add feature login
fixup d4e5f6g WIP: styling
fixup h7i8j9k fix typo in css
fixup l1m2n3o WIP: validation

When you save and exit, Git will combine all four into a single commit named "Add feature login".


4. Reordering and Deleting

  • To Reorder: Simply cut and paste lines in the todo list to change the order in which commits are applied.
  • To Delete: Either change pick to drop or simply delete the entire line from the file.

5. Splitting a Commit

Sometimes you realize one commit is doing too much. To split it:

  1. Mark the commit as edit in the rebase list.
  2. When Git stops, run git reset HEAD~1 to keep the changes but un-commit them.
  3. Use git add -p or git add <file> to create multiple smaller, logical commits.
  4. Run git rebase --continue.

6. Safety and Recovery

Interactive rebase rewrites history. This is perfectly safe for local branches, but never rebase commits that you have already pushed to a shared remote.

If you get lost during a rebase:

git rebase --abort

If you accidentally "lose" a commit during a rebase, don't panic! You can find it using git reflog.

In the next chapter, we'll step beyond your local machine and explore the world of Remote Repositories.