lcaohoanq
371 words
2 minutes
Git Merge vs Rebase vs Squash
Git Merge vs Rebase vs Squash - A Simple Guide
Let’s break down these Git operations in simple terms with practical examples.
Merge: Combining Branches
Merging is like adding your changes alongside others’ work. It creates a new commit that combines two branches.
# Scenario: Merging feature branch into maingit checkout maingit merge feature-branchWhat happens:
Before merge:main: A---B---Cfeature: \ D---E
After merge:main: A---B---C---Ffeature: \ / D---EWhen to use merge:
- When you want to preserve the branch history
- For feature branches that represent complete, logical units of work
- When working on long-running branches
Rebase: Reorganizing History
Rebasing is like moving your changes to start from a different point. It makes history linear and clean.
# Scenario: Rebasing feature branch onto maingit checkout feature-branchgit rebase mainWhat happens:
Before rebase:main: A---B---Cfeature: \ D---E
After rebase:main: A---B---C \ D'---E'When to use rebase:
- When you want a clean, linear project history
- Before merging your feature branch into main
- When updating your feature branch with latest changes from main
Squash: Combining Multiple Commits
Squashing combines multiple commits into one, making history cleaner and more organized.
# Scenario: Squashing last 3 commitsgit rebase -i HEAD~3What happens:
Before squash:A---B---C---D---E
After squash:A---B---F # where F contains changes from C, D, and EReal-World Example
Let’s see how these work together in a typical workflow:
# Start a feature branchgit checkout -b feature/user-authgit commit -m "Add login form"git commit -m "Add validation"git commit -m "Fix typos"
# Main branch has new updates# Option 1: Mergegit checkout maingit merge feature/user-auth
# Option 2: Rebase and Squashgit checkout feature/user-authgit rebase -i main # Squash commits during rebase
# In the rebase interactive editor:pick abc123 Add login formsquash def456 Add validationsquash ghi789 Fix typosQuick Decision Guide
Choose Merge when:
- You want to preserve complete history
- Working with shared branches
- Need to maintain branch context
Choose Rebase when:
- You want a clean, linear history
- Working on a personal feature branch
- Need to integrate latest changes from main
Use Squash when:
- You have multiple small, related commits
- Want to clean up before merging
- Need to simplify history
Best Practices
- Never rebase shared branches
- Squash before merging feature branches
- Use meaningful commit messages
- Keep feature branches short-lived
- Regularly sync with main branch
Remember: There’s no “best” option - each has its use case. Choose based on your team’s workflow and project needs.
Git Merge vs Rebase vs Squash
https://blog.lcaohoanq.works/posts/merge-rebase-squash/