Mastering Git Rebase Interactive: Squashing Commits for a Clean History

Alexander PanovAlexander Panov
2 min read

In the world of Git version control, having a clean, well-structured commit history is essential for both individual developers and collaborative teams. One of the most powerful ways to refine your commit history is through the git rebase -i (interactive rebase) command. A key feature of interactive rebasing is the ability to "squash" commits, merging several smaller commits into one, which helps streamline your history.

What is Git Rebase -i?

The git rebase -i command allows you to interactively modify your commit history. It’s a powerful tool for organizing and restructuring your commits after they’ve been made. By using rebase -i, you can edit, reorder, or even remove commits, allowing you to fine-tune the history before pushing your code to a shared repository.

Why Squash Commits?

Squashing combines multiple smaller commits into one cohesive commit. This is especially useful when you’ve made several incremental changes that don’t need to stand alone in your commit history. By squashing them, you reduce clutter and make your history easier to understand for other developers.

How to Squash Commits with Git Rebase -i

To squash commits, simply run:

$ git rebase -i HEAD~n

Where n is the number of previous commits you want to edit. In the editor that appears, mark the commits to be squashed by replacing pick with squash or fixup. After combining the commit messages, save, and Git will rewrite the history accordingly.

Best Practices for Squashing

It's best to squash commits when finalizing a feature branch or during pull requests. Just be mindful that rewriting history can affect collaborators, so communicate changes clearly.

Ready to take your Git skills to the next level? Sign up for our newsletter for more advanced Git tutorials, tips, and best practices straight to your inbox!

0
Subscribe to my newsletter

Read articles from Alexander Panov directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alexander Panov
Alexander Panov

Software developer and CEO at RoyalZSoftware. I build web applications for startups with Ruby on Rails, Angular and React.