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
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:
| Command | Shortcut | Description |
|---|---|---|
pick | p | Use the commit as is. |
reword | r | Use the commit, but edit the commit message. |
edit | e | Stop for amending (allows you to change files). |
squash | s | Meld into the previous commit; keep both messages. |
fixup | f | Meld into the previous commit; discard this message. |
drop | d | Remove 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
picktodropor simply delete the entire line from the file.
5. Splitting a Commit
Sometimes you realize one commit is doing too much. To split it:
- Mark the commit as
editin the rebase list. - When Git stops, run
git reset HEAD~1to keep the changes but un-commit them. - Use
git add -porgit add <file>to create multiple smaller, logical commits. - 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.