How can I git squash commits to combine my last N commits into a single commit?
I want to merge multiple recent commits into one to keep my Git history clean. What is the correct way to git squash commits while preserving important changes?
How can I git squash commits to combine my last N commits into a single commit?
I want to merge multiple recent commits into one to keep my Git history clean. What is the correct way to git squash commits while preserving important changes?
I’ve done this countless times—interactive rebase is my go-to for squashing commits.
Run:
git rebase -i HEAD~N
(Replace N with the number of commits)
Change
pick
to squash (s)
for all but the first commit
Edit the commit message when prompted
Save & exit to complete the rebase
Boom! Clean history.
Yep, interactive rebase is solid, but sometimes I prefer a quicker way using git reset
.
git reset --soft HEAD~N
(Keeps changes staged)
git commit -m "Squashed commit message"
This method lets you squash commits without an interactive editor. Great for quick fixes!
Good points! But what if you’re working on a feature branch? I like using git merge --squash
:
Switch to
main
: git checkout main
Merge with squash:
git merge --squash feature-branch
Commit:
git commit -m "Merged and squashed feature-branch"
Super useful before merging PRs! Keeps things neat.