Git: squash the latest commits into one

Let’s say you’re working on a new local branch (based on master) and you did multiple commits that are closely related. You might want to squash these latest commits into a single one. Git does not provide a direct way to do this but the steps are pretty much straightforward.

Here is what you need to do in two steps:

First you need to soft reset your working directory to master:

git reset --soft master

This will undo the commits but will leave the changes you did.

Then all you have to do is to commit those changes all together:

git ci -m "your commit message"

In order to simplify these steps you can also add an alias in your git config:

squash = "!f() { git reset --soft master && git ci -m \"$1\"; }; f"

You will then use it this way:

git squash "your commit message"

Of course this is helpful only in the case where (1) your branch is based on the master and where (2) you need to squash all the recent commits of your branch since the master.

If that’s not your case you can change the first step to use HEAD instead, like this for example:

git reset --soft HEAD~3

Which will undo the last 3 commits.

So here you go, how to squash your latest commits into a single one.
You can play with the last command and put the number of the last commits you want to squash as a parameter in the git alias if you want to.

Leave a Reply