If you’ve ever ended up with a heap of noisy, work-in-progress (WIP) commits after a coding sprint, you know how messy a project’s commit history can get. Maintaining a clean, readable Git log is critical—especially for collaborative work and open source contributions. Today, I want to walk you through the powerful Git technique of "squashing commits," helping you present a tidy project history without losing important changes.
Why Squash Commits?
Squashing is the act of combining multiple consecutive commits into one. This is often used during a Git rebase to clean up a feature branch before merging it into main. It’s particularly helpful for:
- Reducing noise: Fewer, more meaningful commits make it easier to track project history.
- Improving clarity: Each squashed commit can reflect a well-defined change or feature.
- Facilitating code reviews: Reviewers appreciate concise, logical changesets.
How to Squash Commits
There are a few ways to squash commits in Git, but the most common method is interactive rebase. Here’s a quick guide:
1. Start Interactive Rebase
git rebase -i HEAD~N
Replace N
with the number of commits you want to squash (e.g., HEAD~3
for the last 3 commits).
2. The Interactive Screen
Your default editor will open a list of the last N commits:
pick 1a2b3c4 Add initial feature blueprint
pick 2b3c4d5 Implement feature logic
pick 3c4d5e6 Fix bug in feature
Change all but the first pick
to squash
or simply s
:
pick 1a2b3c4 Add initial feature blueprint
squash 2b3c4d5 Implement feature logic
squash 3c4d5e6 Fix bug in feature
3. Write a Commit Message
Git will now prompt you to update the commit message for your new, squashed commit. You can combine all messages, summarize, or write a new concise description.
4. Complete the Rebase
Save and close the editor. Git will process the rebase and squash your selected commits into one.
Best Practices for Squashing Commits
- Communicate with your team before rebasing shared branches—rewriting history can impact collaborators.
- Squash in feature branches before merging into main/trunk.
- Use
--autosquash
withrebase
if you’ve usedfixup!
orsquash!
commit prefixes.
Wrapping Up
Squashing commits is an essential Git technique for any developer seeking a clean and understandable history. It’s easy to adopt into your workflow and will vastly improve your team’s experience during code reviews and when tracing changes.
Want more advanced tips? Check out my other articles on Git workflows and histories—let’s keep our repos as clean as our code!
Happy coding!
— Joe Git