How to Merge and Squash in Git

Abdul Jabbar Feb 02, 2024
  1. Git Checkout Branch for Merge
  2. Merge & Squash Branch in Git
  3. Commit Changes to Branch in Git
How to Merge and Squash in Git

Most of the time, we come across a situation while working on a particular working branch, and we have to commit from the working branch to the main branch. But we already have many commits ready for various issues found in the working branch.

This article will discuss how to merge and squash many working commits into a single commit using the git commands. With the help of squash and merge commands in git, we can merge all our desired request’s commits into a single commit and retain a clean history. Squashing the commits helps us clean up our desired branch’s commit history when it accepts our merge request. It puts in all of the changes that we have mentioned in the merge request as a single commit, and afterward, it merges that commit with the help of the merge method specified for the project.

Suppose we have two branches:

  • Working branch
  • Main branch

Git Checkout Branch for Merge

For squashing all the commits of our working branch and merging them into the main branch, we can perform the following steps:

We have to switch to the main branch from the working branch using the git checkout command following:

git checkout main

Merge & Squash Branch in Git

By performing squash, it will take all our commits from the working branch and make one single squash for all commits of the working branch into the main branch. If we face any problems, we can resolve them manually by using the following command:

git merge --squash feature
Note
The above command will not make a merge commit. We have to do it manually using the following command.

Commit Changes to Branch in Git

Now commit merged changes with a combined message.

git commit -m <"add comment here">

If you don’t want to add the commit message, you can skip the -m and comment section, which will not include the message with the commit to the branch.

Author: Abdul Jabbar
Abdul Jabbar avatar Abdul Jabbar avatar

Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.

LinkedIn

Related Article - Git Merge