0
0
GitHow-ToBeginner · 4 min read

How to Squash Commits Using Git Rebase: Simple Guide

Use git rebase -i HEAD~N where N is the number of commits to squash. In the interactive editor, change pick to squash for commits you want to combine, then save and close to merge them into one commit.
📐

Syntax

The basic command to squash commits is git rebase -i HEAD~N. Here, HEAD~N means the last N commits from the current branch. The -i flag opens an interactive editor where you can choose how to combine commits.

In the editor, each commit is listed with the word pick. To squash commits, change pick to squash (or s) for the commits you want to merge into the previous one. After saving, Git will ask you to edit the combined commit message.

bash
git rebase -i HEAD~N
💻

Example

This example shows how to squash the last 3 commits into one. It demonstrates editing the interactive rebase file and the resulting commit history.

bash
git log --oneline -3

# Output before squash:
# 789abcd Initial commit
# d4e5f6a Add feature X
# a1b2c3f Fix typo

git rebase -i HEAD~3

# In the editor, change to:
# pick 789abcd Initial commit
# squash d4e5f6a Add feature X
# squash a1b2c3f Fix typo

# Save and close editor

# Git opens editor to combine commit messages
# Edit message, save and close

git log --oneline -1

# Output after squash:
# 1234567 Combined commit message
Output
789abcd Initial commit d4e5f6a Add feature X a1b2c3f Fix typo [detached HEAD 1234567] Combined commit message 3 files changed, 15 insertions(+), 2 deletions(-) 1234567 Combined commit message
⚠️

Common Pitfalls

  • Choosing wrong commit range: Squashing too many or too few commits by miscounting N in HEAD~N.
  • Confusing pick and squash: Only the first commit should remain pick; others to combine must be squash.
  • Not resolving conflicts: If conflicts occur during rebase, you must fix them and run git rebase --continue.
  • Forgetting to force push: After rewriting history on a shared branch, use git push --force to update the remote.
bash
git rebase -i HEAD~3
# Wrong:
# squash 789abcd Initial commit
# pick d4e5f6a Add feature X
# squash a1b2c3f Fix typo

# Right:
# pick 789abcd Initial commit
# squash d4e5f6a Add feature X
# squash a1b2c3f Fix typo
📊

Quick Reference

CommandDescription
git rebase -i HEAD~NStart interactive rebase for last N commits
pickKeep commit as is
squash (s)Combine this commit into previous one
git rebase --continueContinue rebase after resolving conflicts
git push --forceUpdate remote branch after rewriting history

Key Takeaways

Use interactive rebase with git rebase -i HEAD~N to squash commits.
Change pick to squash for commits to merge into the first one.
Edit the combined commit message when prompted to keep history clear.
Resolve any conflicts during rebase and continue with git rebase --continue.
Force push with git push --force after rewriting commit history on shared branches.