0
0
GitHow-ToBeginner · 3 min read

How to Squash and Merge Pull Request in Git

To squash and merge a pull request, use the git rebase -i command to combine multiple commits into one, then push the changes and merge the pull request on your Git hosting platform using the Squash and merge option. This creates a single commit that represents all changes from the pull request.
📐

Syntax

Use the interactive rebase command to squash commits before merging:

  • git rebase -i HEAD~N: Opens an editor to squash the last N commits.
  • pick: Keeps the commit as is.
  • squash or s: Combines this commit with the previous one.
  • git push --force: Updates the remote branch after rewriting history.

After pushing, use the Git hosting platform’s Squash and merge button to merge the pull request as a single commit.

bash
git checkout feature-branch
git rebase -i HEAD~3
# In editor, change 'pick' to 'squash' for commits to combine
git push --force origin feature-branch
💻

Example

This example shows how to squash the last 3 commits on a feature branch and push the changes before merging the pull request.

bash
git checkout feature-branch
# Start interactive rebase for last 3 commits
git rebase -i HEAD~3
# In the editor, change lines from 'pick' to 'squash' for commits 2 and 3
# Save and close the editor to combine commits

git push --force origin feature-branch
Output
Successfully rebased and updated refs/heads/feature-branch To github.com:user/repo.git + abc1234...def5678 feature-branch -> feature-branch (forced update)
⚠️

Common Pitfalls

  • Forcing push without coordination: Force pushing rewrites history and can confuse collaborators if not communicated.
  • Squashing too many commits: Squash only related commits to keep history meaningful.
  • Not updating local branches: After force push, others must reset their local branches to avoid conflicts.
  • Using merge instead of squash on GitHub: Choose the Squash and merge option on the pull request page to keep history clean.
bash
## Wrong: Pushing without rebase

git push origin feature-branch

## Right: Rebase and squash before pushing

git rebase -i HEAD~3
git push --force origin feature-branch
📊

Quick Reference

ActionCommand or Step
Start interactive rebasegit rebase -i HEAD~N
Mark commits to squashChange 'pick' to 'squash' in editor
Force push changesgit push --force origin branch-name
Merge pull requestUse 'Squash and merge' button on GitHub/GitLab
Communicate changesInform team about force push

Key Takeaways

Use git rebase -i to combine multiple commits into one before merging.
Always force push after rebasing to update the remote branch.
Choose the 'Squash and merge' option on your Git hosting platform to merge cleanly.
Communicate with your team before force pushing to avoid conflicts.
Squash related commits only to keep project history clear and meaningful.