git_rebase_vs_merge
git rebase vs merge
When to use rebase and when to use merge.
π Visual Comparison
Before
main: A---B---C
\
feature: D---E
After Merge
git checkout main
git merge feature
main: A---B---C-------M
\ /
feature: D---E----
Creates merge commit
Mpreserving both histories.
After Rebase
git checkout feature
git rebase main
main: A---B---C
\
feature: D'---E'
Replays commits on top of main with new hashes.
π Comparison Table
| Aspect | Merge | Rebase |
|---|---|---|
| History | Non-linear, preserves context | Linear, clean |
| Commits | Original hashes kept | New hashes created |
| Conflicts | Resolve once | Resolve per commit |
| Safety | Safe for shared branches | β οΈ Don't use on shared |
| Use case | Shared branches, releases | Feature branches |
β When to Use Merge
Merge Main into Feature
git checkout feature-branch
Switch to feature.
git merge main
Merge main into feature to get latest changes.
Merge Feature into Main
git checkout main
Switch to main.
git merge feature-branch
Merge completed feature.
Merge for Public/Shared Branches
git merge --no-ff feature-branch
Always use merge for branches others are using.
β When to Use Rebase
Rebase Feature onto Main
git checkout feature-branch
Switch to feature.
git rebase main
Rebase your commits onto latest main.
Pull with Rebase
git pull --rebase origin main
Fetches and rebases instead of merging.
Configure Always Rebase on Pull
git config --global pull.rebase true
Makes
git pullalways rebase.
Interactive Rebase for Cleanup
git rebase -i HEAD~3
Clean up last 3 commits before merging.
π Decision Flowchart
graph TD
A[Combine branches?] --> B{Shared/public branch?}
B -->|Yes| C[Use Merge]
B -->|No| D{Feature branch?}
D -->|Yes| E{Clean history needed?}
D -->|No| C
E -->|Yes| F[Use Rebase]
E -->|No| C
β οΈ Golden Rules
Never Rebase Public Branches
# β DON'T DO THIS
git checkout main
git rebase feature
Never rebase main or shared branches.
Safe to Rebase Private Branches
# β
SAFE
git checkout my-feature
git rebase main
Rebase your own feature branch onto main.
π Recommended Workflow
1. Work on Feature Branch
git checkout -b feature/new-thing
Create feature branch.
2. Regularly Rebase onto Main
git fetch origin
Get latest from remote.
git rebase origin/main
Rebase onto latest main.
3. Before PR, Clean Up
git rebase -i HEAD~5
Squash/reword commits.
4. Create PR
gh pr create
Submit pull request.
5. Merge with Squash (GitHub)
On GitHub, use "Squash and merge" for clean history.
π‘ Tips
Always rebase feature onto main before creating PR.
After rebasing a pushed branch:
git push --force-with-lease
Merge is safer and easier to understand.
π Related
#git #rebase #merge #comparison #workflow