Advanced Git: Interactive Rebase
Interactive rebase is one of Git's most powerful features for rewriting history, allowing you to modify, reorder, squash, or drop commits before pushing them to a shared repository. While git rebase
is useful on its own, the interactive mode (triggered with git rebase -i
) gives you surgical control over your commit history.
When you run git rebase -i HEAD~3
, Git opens your default editor with the last three commits listed in reverse chronological order. Each commit is prefixed with the word "pick". By changing these keywords, you can perform different actions: "reword" to change the commit message, "edit" to modify the commit's contents, "squash" to combine it with the previous commit, or "drop" to remove it entirely.
One common use case is cleaning up a feature branch before merging. Perhaps you made several small commits while working through a problem, each with messages like "WIP" or "fix typo". Before merging, you can squash these into a single, well-documented commit that clearly describes the feature. This creates a cleaner, more readable project history.
However, interactive rebase should be used carefully. Never rebase commits that have already been pushed to a shared branch, as this rewrites history and can cause conflicts for other developers. Always communicate with your team when performing history-rewriting operations, and consider using feature branches for experimental work where you have the freedom to clean up commits before merging.