Git Rebase vs Merge

Understanding the difference between rebase and merge in Git.

Git Merge

Basic merge
git checkout main
git merge feature-branch

Creates merge commit
• Preserves complete history
• Shows when branches were merged
• Non-destructive operation
• Creates a merge commit

Fast-forward merge
git merge --ff-only feature-branch
// Only if no divergence

No fast-forward
git merge --no-ff feature-branch
// Always create merge commit

Abort merge
git merge --abort

Git Rebase

Basic rebase
git checkout feature-branch
git rebase main

What it does
• Moves entire branch to new base
• Rewrites commit history
• Creates linear history
• No merge commits

Interactive rebase
git rebase -i HEAD~3
// Edit last 3 commits

Rebase options
pick // Use commit
reword // Edit commit message
edit // Amend commit
squash // Combine with previous
fixup // Squash without message
drop // Remove commit

Continue/abort rebase
git rebase --continue
git rebase --abort
git rebase --skip

Merge vs Rebase Comparison

When to use MERGE
✓ Merging public branches
✓ Want to preserve history
✓ Showing collaboration
✓ Safe for shared branches
✓ Easier to understand for beginners

When to use REBASE
✓ Cleaning up local commits
✓ Linear history desired
✓ Before creating PR
✓ Private feature branches
✓ Squashing commits

⚠️ NEVER rebase
✗ Public/shared branches
✗ Commits pushed to remote
✗ When others are working on branch

Common Workflows

Update feature branch with main
Option 1: Merge
git checkout feature
git merge main

Option 2: Rebase
git checkout feature
git rebase main

Squash commits before merge
git rebase -i HEAD~5
// Squash last 5 commits
git checkout main
git merge feature

Pull with rebase
git pull --rebase origin main
// Avoid merge commits when pulling