Rebase
Replay commits on top of another branch
Skills taught: git.rebase, git.interactive-rebase
Basic rebase — update your branch
# Before:
# main: A---B---E---F
# feature: \---C---D
# Switch to your feature branch
git switch feature/login
# Rebase onto main
git rebase main
# After:
# main: A---B---E---F
# feature: C'---D' (new hashes — replayed on top of F)
# C' and D' have the same content as C and D,
# but different hashes (because their parent changed)
Warning: Golden rule: Never rebase commits that have been pushed to a shared branch. Rebasing rewrites history — teammates who pulled your old commits will have diverging history.
Interactive rebase — clean up your history
Before opening a PR, use interactive rebase to squash WIP commits, fix typos in messages, or drop unnecessary commits.
# Interactively edit the last 3 commits
git rebase -i HEAD~3
# An editor opens with something like:
# pick a1b2c3 Add login form HTML
# pick d4e5f6 WIP fix
# pick 7a8b9c Fix typo
#
# Commands:
# p, pick = use commit as-is
# r, reword = use commit, but edit the message
# s, squash = combine with the previous commit
# f, fixup = like squash but discard this commit's message
# d, drop = remove the commit
# Change to:
# pick a1b2c3 Add login form HTML
# squash d4e5f6 WIP fix
# fixup 7a8b9c Fix typo
# Result: all 3 commits become one with a combined message
Rebase vs Merge — when to use each
# Scenario 1: Update feature branch with latest main
# ✅ Use rebase — keeps feature branch linear
git switch feature/login
git rebase main
# Scenario 2: Integrate feature branch into main
# ✅ Use merge — preserves branch history
git switch main
git merge --no-ff feature/login
# Scenario 3: Clean up commits before a PR
# ✅ Use interactive rebase
git rebase -i HEAD~5
Frequently Asked Questions
I rebased and now my push is rejected. What do I do?
After rebasing a branch you already pushed, the remote's history and your local history have diverged. You need to force push: git push --force-with-lease (safer than --force — it checks no one else pushed). Only do this on personal feature branches, never on main.
What does git rebase --onto do?
It's for advanced situations where you want to replay commits from one branch onto a different target. For example, if feature-b branched off feature-a, and you want feature-b on main directly: git rebase --onto main feature-a feature-b.