Git

How Do You Squash All Commits in One?

In Git Squash is a technique that allows you to make a series of changes on commits and then consolidate it into one commit. Let’s explain with the help of an example, suppose you have n number of commits and when you apply git squashing on them, you can squash or compress all ‘n’ commits into a just single commit. Git squash is used to change several large commits into a small single meaningful commit. So, you can make the git log clearer. You can also merge branches using the squashing technique. It is a best practice to always squash commits and rebase it with the master or parent branch.

This article will elaborate you how to Squash all commits in a single commit in git. We have implemented all steps on the CentOS 8 Linux distribution.

Squash Commits into one with git

You can implement the git squashing into the following steps:

Step 1: Choose Start commit

To determine how many commits you need to squash, the following command you will run on the terminal:

$ git log

Now, you will invoke the git to start an interactive rebase session by using the following command:

$ git rebase -i HEAD~N

In the above HEAD~N, the ‘N’ is the total number of commits you have determined from the ‘git log’ command. Let’s assume, the number of commits is 4. Now, the command will change into the following form:

$ git rebase -i HEAD~4

The following commits list will display on the terminal where each commits staring with the word pick.

Step 2: Change Pick into Squash 

Here, we will mark all commits as squashable, leave the first commit that will be used as a starting point. So, change the vim editor into the insert mode by pressing ‘i’ and change the all pick commit into the squash except the first commit. Now, press ‘Esc’ to change the insert mode and press ‘:wq!’ to save all changes and quit. If you are using the simple text editor then, you can simply change the ‘pick’ word into the ‘squash’ and save changes. After that, you will see the following window on the terminal:

When you will leave this shell, you will see the following messages on the terminal window:

If you will squash all then, you will see all commits combined into a single commit statement that will display on the terminal:

Conclusion

By using the git squash, you can easily squash or compress many commits into a smaller single commit. You can use this technique to fix documentation spelling mistakes. We have implemented git squash in this article. We have also seen how we can make history clean using the git rebase and squash commands.

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.