A practical way to squash git commit

Manish Kumar
3 min readMar 21, 2021

If you have worked on git ever then you must have encountered the way to manage multiple commits. Well, why this is important?

Let’s say you are working on a feature. This feature has many changes and you work and commit the changes to a branch (say feature). After some days you will see there are multiple changes has accumulated in the different commits, isn’t it? and these look weird and not important to keep all these related changes to the feature in several commits instead we can club all these commits together.

How would we tackle this situation?

We have to use something called the squash technique. we can squash all these several commits into one commit. To do the git squash we use git-rebase. git rebase is a very powerful swiss army knife. It helps in almost any situation.

To illustrate this I will take an example. We are working on a repository. See below the last commit of the master. Notice the last commit.

Now we created a feature branch (say feature) and committed some changes to it. There is three commits you can see in the below picture, and all these belong to similar feature.

How to use interactive git rebase here?

Step 1) Note the last good commit. (may be commit from where you checked out the feature branch)

Step 2) In this case lets say last good commit was 89716abbb7473f18521d51632da75b36d3184ced. So we will start rebase in interactive mode from that commit. Here -i will start the rebase in interactive mode.

git rebase -i 89716abbb7473f18521d51632da75b36d3184ced

Once you execute the above command it will bring this interactive screen. You will find all your commits here on the screen (in this case it's three).

Now to club them into one we have to squash the other two. To do so manually edit this file and change pick to squash. The screen will look like this:

Now save this file it will convert all three commits into one. To verify use git log. You can see all three commits are merged into one. You can format the commit message as well.

Now push this commit to the feature branch

git push -f origin featureNote :- The -f is required here because of the rebase. Whenever you do a rebase you would need to do a force push because the remote branch cannot be fast-forwarded to your commit.

At the remote repository, you will see something like this.

Before: Three different commit

After: Squashed all the three commits into one.

This helps us to keep git clean and will manage the unnecessary commit smoothly.

Hope this article has helped you. Happy Learning!!!

--

--