This guide demonstrates how to combine multiple commits into a single commit using Git's interactive rebase feature.
Squashing commits is useful when you want to:
- Clean up your commit history before merging
- Group related changes into a single logical commit
- Simplify your project's history for better readability
First, check your commit history to identify how many commits you want to combine:
git log --oneline -n 10
This will show your 10 most recent commits, allowing you to count how many you want to squash.
Use the interactive rebase command, specifying how many commits to go back:
git rebase -i HEAD~N
Note: Replace
N
with the number of commits you want to include in the rebase.
Your text editor will open showing something like this:
pick abc1234 Most recent commit message
pick def5678 Second most recent commit
pick ghi9012 Third most recent commit
# ... and so on
Change all instances of pick
to squash
(or just s
) except for the first commit:
pick abc1234 Most recent commit message
s def5678 Second most recent commit
s ghi9012 Third most recent commit
# ... and so on
π‘ Tip: Using pick for the first commit and squash for the rest tells Git to combine all commits into the first one.
After saving and closing the rebase plan, another editor window will open allowing you to create a new commit message for the combined commit:
# This is a combination of N commits.
# The first commit's message is:
Most recent commit message
# This is the 2nd commit message:
Second most recent commit
# ...
Edit this to create your final commit message, then save and close.
Once the rebase is complete, push your changes with the force flag:
git push --force origin main
β οΈ Note: Replacemain
with your branch name if different. Force pushing is necessary because the commit history has been rewritten.
β οΈ Warning: Force pushing rewrites history on the remote repository. Use with caution, especially on shared branches.
- Only squash commits that haven't been shared with other developers
- Communicate with your team before force pushing to shared branches
- Consider using --force-with-lease for a safer force push:
git push --force-with-lease origin main
- Back up your repository before performing complex Git operations
If your changes are in a feature branch, you can also squash when merging:
git checkout main
git merge --squash feature-branch
git commit -m "Combined commit message"
Happy coding! π