Blog>

How to Squash Last N Git Commits Without Rebasing

1 minute read

How to Squash Last N Git Commits Without Rebasing

If you've been bashing away at a problem and had to commit a few times to get it right - squashing is a great way to tidy up and cover your tracks.

Always do this on a test branch to check it does what you need before applying it to you work!

Here's the quick way to squash your last N consecutive Git commits into a single commit with a new message without a rebase.

Lets set the scene; maybe your Git history looks something like this:

$ git log --oneline a1b2c3d Jesus christ, seriously fix the stupid header styles b2c3d4e Actually fix header styles c3d4e5f Fix header styles d4e5f6g Add header component and baseline styles

You probably don't want those increasingly desperate commit messages sitting in your Git history.

Replace N with the number of commits you want to squash:

git reset --soft HEAD~N

In this example, we're squashing the last 4 commits:

git reset --soft HEAD~4

This removes the commits from your history but keeps all their changes staged.

Now commit everything as a single, clean commit:

git commit -m "feat: update header styles"

Your history is now:

$ git log --oneline e5f6g7h feat: Implement header component with baseline styling

Much better.

Because you've rewritten your local history, you'll need to force push:

git push --force-with-lease

--force-with-lease is preferable to --force because it checks that nobody else has pushed to the branch since you last fetched.