CPCODELAB
Git & GitHub

Rebase and When to Use It

12 min read

What Is Rebase?

git rebase moves or replays a sequence of commits onto a different base commit. It rewrites history, producing a cleaner, linear commit graph — as if you had always branched off the latest version of main.

bash
# Rebase your feature branch on the latest main
git switch feature/login
git fetch origin
git rebase origin/main

Merge vs Rebase

  • Merge preserves the full branching history. Good for long-lived shared branches.
  • Rebase rewrites history for a cleaner log. Good for keeping feature branches tidy before a PR.

The Golden Rule of Rebase

Never rebase commits that have been pushed to a shared branch. Rebasing rewrites SHAs. If others have based work on those commits, they will have diverged history and painful reconciliation ahead.

You may safely rebase your own feature branch even after pushing, as long as only you are working on it. Force-push carefully: git push --force-with-lease origin feature/login. The --force-with-lease flag fails if someone else has pushed to that branch since your last fetch — a useful safety net.

Ready to test yourself?
Practice Git & GitHub— quiz & coding exercises