Git is an incredibly powerful version control system, but many developers only use a fraction of its capabilities. If your commit history is a mess of "wip", "fixed bug", and "typo", it's time to learn interactive rebase.
Interactive rebase (`git rebase -i`) allows you to rewrite commit history. You can squash multiple commits into one, reword commit messages, edit the contents of a commit, or even drop a commit entirely.
The Golden Rule of Rebasing
Never rebase commits that have already been pushed to a public, shared repository. Rebasing rewrites history, which will cause merge conflicts for anyone else who has pulled the original history.
1. Starting an Interactive Rebase
To start an interactive rebase, you need to tell Git how far back in history you want to go. For example, to rebase the last 3 commits:
This will open your default terminal text editor (usually Vim or Nano) with a list of the last 3 commits.
2. The Rebase Commands
In the editor, you'll see a list of commits starting with the word `pick`. You can change `pick` to any of the following commands:
- reword (r): Keep the commit, but let me edit the commit message.
- edit (e): Pause the rebase at this commit so I can add or remove files.
- squash (s): Melt this commit into the previous commit.
- drop (d): Delete this commit from history entirely.
Squashing Commits
Squashing is perfect for cleaning up a messy feature branch before opening a Pull Request. You can squash 10 "WIP" commits into a single, clean "Added Login Feature" commit.
Conclusion
Interactive rebase is the secret weapon of senior developers. It allows you to curate a pristine, readable Git history that makes code reviews a breeze.