Git - Squashing Commits Using Rebase

July 9, 2023

Squashing Commits

In the last post, we covered the "git log" command, amending commit history, and using an interactive rebase session to reorder commit history locally.

 

In this post, we're going to cover squashing commit history, a feature of the rebase command. Squashing commits allows you to combine multiple commits into one single commit.

Why is this useful? Suppose you're working on one feature or bug fix and have multiple commits locally to track changes along the way. But before you push to your remote repository, you want to clean up the commits into one so that other team members who pull your changes see the work all combined. This can make it easier for team members to understand your changes.

Squashing commits and using the rebase command does come with a caveat.

 

#1 Rule to Rebase: Don't use it if you don't know exactly what you're doing!

 

The rebase command is a powerful but potentially dangerous tool, because it has the ability to rewrite commit history. If not used properly, it can cause data loss, cause headaches for team members, and reorder the logical development history of the project which can cause confusion. Use with care!

 

We'll go through a simple example of squashing a few commits.

 

Here I have added 4 new commits with the following message and added these new files:

  • "File One Commit" - one.txt
  • "File Two Commit"- two.txt
  • "File Three Commit"- three.txt
  • "File Four Commit"- four.txt

Here's the git log:

We'll run the rebase command for the last three commits "git rebase -i HEAD~3" which bring us to the following interactive rebase session.


We're now brought into the Vim text editor. If you're not familiar with Vim, I encourage you to look for resources and tutorials online. For the commit that we want to condense the history under, we'll leave the keyword "pick" next to the commit message. To edit text in the Vim text editor, we first need to hit the i key on the keyboard. For the commits that we want to condense, we'll change the word "squash" to condense those commits into the commit where we specified "pick".

Take a look:

We'll now save and exit using [ESC] :wq

We'll now be brought to a screen where we can edit the commit messages for the combined squash commit.

Here I'll just leave the commit message as they appear on the screen and hit [ESC] :wq on the keyboard to write the changes and exit. This brings me to this message:

This has let us know that we've successful squashed our commits.

 

Here is revised git log:

Success! I hope this was helpful and stay tuned for more posts on git rebase coming soon!