How to squash the git commits

Git Squash

"Squashing" in git means combining the multiple commits into a single commit. So that we can make
the history of the repository cleaner. In this blog post, let's see how we can perform
the git squash using the git rebase command.

Assumption

  • Planning to create a pull request from the "feature/add-header" branch to the "main" branch
  • Pushed 4 new commits into the "feature/add-header" branch

Steps

Now, let's see the step by step process to squash the commits.

1. Move to the working branch

git checkout feature/add-header

2. Check the history of commits using the git log command

git log --oneline







Totally, we can see 5 commits from the git log command. For the main branch, HEAD is pointing
to the first commit. For the feature/add-header branch, HEAD is pointing to the fifth commit.
Before we merge the feature/add-header branch with the main branch, we have to combine the
second, third, fourth and fifth commits. Let's see how it is done.

3. Move the HEAD

Since we would like to squash the last 4 commits, note down the commit ID of the first commit
Here the commit ID of the first commit is 2ae87c2, so the command would be,

git rebase -i 2ae87c2

4. Pick and Squash

After this, the interactive editor opens with the file where we can see the list of commits.

Here, squash the commits by replacing the word 'pick' before the commit ID with the letter 's'
After the modification, the editor will look like below, save and close the file.



Once we close the previous file, another file opens up with the list of the commit messages.



Remove/Comment unnecessary commit messages from the file, keep at least a single commit message.
Save and close the file.




5. Verify the commit history

If we see the history of commits using the git log command, only the two commits would be visible.



Comments