my-notes

git_rebase_vs_merge

2 min read

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 M preserving 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 pull always 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.


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

Rebase After Pick

Always rebase feature onto main before creating PR.

Force Push After Rebase

After rebasing a pushed branch:

git push --force-with-lease
Prefer Merge for Beginners

Merge is safer and easier to understand.



#git #rebase #merge #comparison #workflow

Built with mdgarden