0
0
GitHow-ToBeginner · 3 min read

How to Squash Merge in Git: Simple Steps and Examples

To squash merge in Git, use git merge --squash branch-name to combine all commits from the branch into a single commit on your current branch. Then, commit the changes with git commit to finalize the squash merge.
📐

Syntax

The basic syntax for squash merging in Git is:

  • git merge --squash <branch-name>: Combines all commits from the specified branch into your current branch as staged changes without creating a merge commit.
  • git commit: Creates a single commit from the staged changes, completing the squash merge.
bash
git merge --squash feature-branch
git commit -m "Squash merge feature-branch"
💻

Example

This example shows how to squash merge a branch named feature-branch into main. It combines all feature-branch commits into one commit on main.

bash
git checkout main
# Merge feature-branch with squash
git merge --squash feature-branch
# Commit the combined changes
git commit -m "Add feature from feature-branch as a single commit"
Output
Updating files: 100% (5/5), done. [main 1a2b3c4] Add feature from feature-branch as a single commit 5 files changed, 50 insertions(+)
⚠️

Common Pitfalls

Common mistakes when squash merging include:

  • Not running git commit after git merge --squash, which leaves changes staged but uncommitted.
  • Expecting a merge commit; squash merge creates a single new commit instead.
  • Forgetting to update the branch after squash merge, which can cause conflicts if you later merge normally.
bash
# Wrong way:
git merge --squash feature-branch
# Forgot to commit

# Right way:
git merge --squash feature-branch
git commit -m "Squash merge feature-branch"
📊

Quick Reference

CommandDescription
git merge --squash Prepare all changes from as staged changes
git commit -m "message"Create one commit from staged changes
git statusCheck staged changes before committing
git logView commit history after squash merge

Key Takeaways

Use git merge --squash to combine multiple commits into one before merging.
Always run git commit after squash merging to finalize the changes.
Squash merge does not create a merge commit but a single new commit.
Check your staged changes with git status before committing.
Be careful to update branches properly to avoid conflicts after squash merges.