When working on a feature or bug fix, you may end up with several commits that clutter your Git history—like “fix typo,” “update formatting,” or “test change.” Squashing commits helps you combine multiple commits into one clean, meaningful commit before merging into the main branch.
This guide shows you how to squash commits using both GitHub’s pull request interface and the Git command line.
✅ What Is Squashing?
Squashing commits means merging multiple commits into one. It’s useful for:
- Cleaning up commit history
- Grouping related changes into one logical unit
- Improving readability of Git logs
🟢 Option 1: Squash Commits via GitHub Pull Request
This is the easiest and most common method in collaborative projects.
Steps:
- Create a pull request from your feature branch to the
main
(ormaster
) branch. - After approval, click the “Merge pull request” dropdown.
- Select “Squash and merge”.
- Edit the commit message (optional) to summarize the change.
- Click Confirm squash and merge.
✅ Done! All commits in the PR will be combined into a single commit on the main
branch.
Note: You must have write access to the repository to use this feature.
🛠️ Option 2: Squash Commits Locally Using Git CLI
This gives you full control before pushing to GitHub.
1. View commit history:
git log --oneline
Identify how many commits you want to squash (e.g., last 3).
2. Start interactive rebase:
git rebase -i HEAD~3
This opens an editor with something like:
pick a1b2c3 First commit
pick d4e5f6 Fix spacing
pick f7g8h9 Add comments
3. Change all but the first pick
to squash
or s
:
pick a1b2c3 First commit
squash d4e5f6 Fix spacing
squash f7g8h9 Add comments
4. Save and close the editor.
Another window opens to edit the new commit message. You can:
- Combine messages
- Keep only one message
- Write a new one
After that, Git squashes the commits.
5. Push the changes:
If this branch was already pushed, force-push the updated history:
git push origin branch-name --force
⚠️ Only use
--force
if you’re confident and working on a feature branch, not shared production branches.
📝 Summary
Method | Tool | Use When |
---|---|---|
Squash & Merge button | GitHub UI | Merging pull requests |
git rebase -i | Git CLI | Full control before pushing |
Squashing commits keeps your Git history clean and professional. It’s especially helpful before merging to main
, during code reviews, or when submitting pull requests to open source projects.