What is the difference between git merge and git rebase?

Merge preserves full history with a merge commit; rebase replays commits on top of another branch for a linear history.

GitVersion Control

Overview

Both `git merge` and `git rebase` integrate changes from one branch into another but they do it differently and produce different histories. `merge` is non-destructive: it creates a merge commit that ties two branches together. `rebase` rewrites history by replaying your commits on top of the target branch, producing a perfectly linear history.

Key Points

  • •Merge is safe for shared branches it never rewrites existing commits.
  • •Rebase produces a cleaner, linear history with no merge commits.
  • •Never rebase commits that have already been pushed to a shared remote branch.
  • •`git pull --rebase` is a popular convention to keep your local commits on top without a merge commit.
  • •Use `git rebase -i` (interactive rebase) to squash, edit, or reorder commits before merging.

Examples

Merge feature branch into main (creates a merge commit)

bash
git switch main
git merge feature/login

History shows a diverge-and-join. Safe for shared branches.

Rebase feature branch onto main (linear history)

bash
git switch feature/login
git rebase main

Commits from feature/login are replayed on top of the latest main.

Interactive rebase: squash last 3 commits into one

bash
git rebase -i HEAD~3
# In the editor, change "pick" to "squash" (or "s") for commits to combine

Great for cleaning up WIP commits before a PR.

Pull with rebase instead of merge

bash
git pull --rebase origin main

Keeps your local commits on top without a "Merge branch" commit.

Pro Tip

A simple rule: use `merge` for integrating long-lived branches (e.g. feature → main) and `rebase` for keeping a feature branch up-to-date with main while you work. Never rebase public/shared history.