I created a new branch from master and made around 20 commits.
I want to squash all commits on this branch into one. I know git rebase -i HEAD~20
works if I know the commit count, but is there a way to squash commits on a branch without counting commits manually?
Yeah, I usually find the commit where my branch started using:
git merge-base master HEAD
Then I squash everything on top of that with:
git rebase -i $(git merge-base master HEAD)
This way, I don’t have to remember how many commits I made. It works as long as master is your base, adjust if you branched off something else.
My go-to method is:
git reset --soft origin/master
git commit -m "Your single commit message"
It resets everything to the point where I branched off but keeps my changes staged.
Then I just commit once. It’s clean and quick, no interactive rebase needed.
I wrote a little script that auto-squashes all commits on my current branch compared to main. It finds the common ancestor and rebases:
git rebase -i $(git merge-base main HEAD)
I use it whenever I’m about to open a PR. It’s saved me from a lot of back-and-forth clean-up later.
Just make sure your working directory is clean before rebasing.