Sobes.tech
Middle
202

What is the difference between rebase and merge in Git?

Answer from AI

sobes.tech AI

Merge combines branches, creating a new merge commit. Rebase moves commits from one branch onto another, rewriting history.

Merge:

  • Preserves the history of changes in its original form.
  • Creates a new commit.
  • Easier to track the origin of changes.

Rebase:

  • Creates a linear history.
  • Does not create a new merge commit.
  • Rewrites commit history.
  • Can cause issues when collaborating if the history has already been published.

Comparison:

Property Merge Rebase
History Linear with branches (merge commit) Linear (rewrites history)
Commits Adds a new merge commit Moves existing commits to a new place
Tracking Easier to understand where changes came from Can make tracking more difficult
Collaboration Recommended for published branches Not recommended for published branches

Merge Example:

// Switch to the target branch
git checkout main

// Merge feature branch
git merge feature

Rebase Example:

// Switch to the branch to be rebased
git checkout feature

// Rebase feature branch onto main
git rebase main