Squash merging

Suppose we have a branch called bugfix where we fixed a bug in a hurry. In this branch, we did two commits: B1 and B2. But because we were in a hurry, these are not very good commits. So now we need to merge them into master but instead of using a three-way merge, we are going to create a squash merge. In this type of merge, we create a new commit which is the combination of all the commits in our branch but has no ancestry to the tip of the branch (in this example, commit B2).


Once we squash merge we can (and should) delete the bugfix branch. Though this technique produces clean linear histories on the master branch, it should only be used for short-lived branches with small changes and dirty commit histories.

Squash merging 1
Squash merging 2

As an example, let's create a new branch called bugfix. In this branch, we'll create two new commits, one that modifies audience.txt and one that modifies toc.txt.


Now we switch onto the master branch. In order to merge the bugfix branch onto master, we run

git merge --squash bugfix

If we check the status of our repository we see that our changes are now available on master, but they are not committed. We need to create a commit with these changes, and give it a meaningful message that explains the merge.

If we check the log now, we will see that our bugfix branch has two commits: 3accc2f and 2de4c95. Our master branch is at commit 6166e28 which is our squash merge commit, but this commit is not connected to the tip of the bugfix branch.


Since the branch was not merged on to master, it is very important that we delete it. Otherwise, it will cause confusion in the future once we have moved on from this bug and no one even remembers what that branch was supposed to do.

Squash merging 3