Squash Multiple Git Commits

I'm learning a lot on my journey to contributing to open-source. One of the things I have learned recently is to squash git commits. You're not alone if you don't know what this means, I also didn't know what it meant the first time I heard it.

In this article, I would like to help you understand what squashing git commits is and why it matters. I'll also show you how to squash multiple git commits.

Squashing

Squashing git commits is a technique that allows you to condense multiple commits into a single commit, making it easier to read and understand the commit history of your repository.

This is particularly useful when working on a feature or bugfix that is spread across multiple commits, as it allows you to present the changes as a single, cohesive unit. Squashing commits can also be useful when you want to reorganize your commit history, or if you have made commits that contain sensitive information that should not be publicly accessible.

Additionally, squashing commits can make it more efficient to work on pull requests, by making it easier to review the changes introduced. It also allows for keeping a cleaner and more readable commit history of your repository.

How to squash commits

To demonstrate how to squash commits, I have opened a Pull Request with multiple commits:

There are different ways to squash git commits, one of the most common is to use the git rebase command.

We'll go to our branch and type:

git rebase -i HEAD~5

We're using the git rebase command with the -i flag to interactively choose which commits to squash. 5 tells the command to select the last 5 commits from our current commit.

The command opens up a text editor as shown:

Nothing happens when we type in the editor. We need to enable that by pressing the i key on the keyboard. This enables us to insert characters in the editor.

Next, we'll type either squash or s before the commit we want to squash:

Once we are done editing the file, we need to press the escape key, Esc, to disable insert. We type :x to close the editor and press Enter:

After closing the previous file in the editor, we are redirected to this file. It keeps track of the commit messages:

Remove the previous commit messages and add a new commit message:

We are now ready to push to our branch. However, git push returns an error:

We can get rid of the error by adding the --force flag to our git push command:

After a successful git push, we can see in our Pull Request that our multiple commits have been squashed into a single commit:

Conclusion

In this article, we have looked at what is squashing git commits and why it is important to squash git commits. We have also looked at how to squash git commits.