Squash and Merge in Git Explained with Examples

In previous blogs, we explored fast forward merges and three-way merges. Now it’s time to learn about another merging strategy: squash and merge.

Squash and merge is used when you want to combine multiple commits into a single clean commit before merging into main.


Why Use Squash and Merge?

Imagine your feature branch has 50–60 small commits.
If you merge normally (fast forward or three-way), all of those commits clutter your history.

With squash and merge, you can compress them into one commit, keeping history simple and clean.


Project Setup

mkdir project4
cd project4
git init

Make some commits on main:

echo "Hello World" > hello.txt
git add .
git commit -m "Initial commit"

echo "Feature 1" > feature1.txt
git add feature1.txt
git commit -m "Add feature1 file"

Creating a Feature Branch

Now create a feature branch:

git switch -C feature/video

Add multiple commits:

echo "video feature 1" > video_feature1.txt
git add video_feature1.txt
git commit -m "Add video feature 1"

echo "video feature 2" > video_feature2.txt
git add video_feature2.txt
git commit -m "Add video feature 2"

Now feature/video has two commits.


Diverging Main Branch

Switch back to main and add another commit:

git switch main
echo "extra file on main" > main_file.txt
git add main_file.txt
git commit -m "Add extra file on main"

Squash and Merge

Instead of a normal merge, run:

git merge --squash feature/video

Output:

Squash commit -- not updating HEAD

All changes from feature/video are staged in main, but no commit is created yet.

Check files:

ls
# hello.txt feature1.txt main_file.txt video_feature1.txt video_feature2.txt

Now make a single commit:

git commit -m "Add video feature (squashed)"

Visualizing the Merge

Before Squash



After Squash Merge


Here, instead of merging branch history, Git created one clean commit.


Important Notes About Squash and Merge

  • Branch listing mismatch: After squash, running:

    git branch --merged
    

    will not show feature/video as merged.

    And:

    git branch --no-merged
    

    will still list feature/video.

  • Branch deletion: Because Git thinks the branch is not merged, deleting requires a force delete:

    git branch -D feature/video
    
  • Garbage collector: Dangling commits from feature/video will eventually be removed by Git’s garbage collector.


Summary

  • Squash and merge combines multiple commits into one clean commit.
  • Keeps commit history simple.
  • Useful when a feature branch has many small commits.
  • git branch --merged will not reflect squash merges.
  • Branch deletion requires -D.

Keep Learning 🚀

👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.

👉 My YouTube Channel – More videos, more fun, and lots of learning!

👉 📺 Watch this topic in video form

Stay curious, keep coding, and let’s make learning fun together! 🎉