Rebasing & History Rewriting
Rewrite commit history for a clean, linear log — and learn when not to.
Rebase replays your commits on top of another branch, producing a linear history instead of a merge commit. It rewrites commit hashes, so the result is tidier but the commits are technically new.
Interactive rebase (git rebase -i) lets you clean up before sharing:
squash several WIP commits into one, reword messages, reorder, or
drop commits. The golden rule:
# Bring your feature branch up to date on top of main
git switch feature/x
git rebase main
# Clean up the last 3 commits before opening a PR
git rebase -i HEAD~3
# pick abc Add form
# squash def fix typo
# squash 012 fix again
# If conflicts arise mid-rebase:
git status # resolve, then:
git add <file>
git rebase --continue # or: git rebase --abort - Make three small commits, then squash them into one with interactive rebase.
- Rebase a feature branch onto an updated main and resolve any conflict.
- Reword an earlier commit message using
git rebase -i. - Explain why you’d use
git revertinstead of rebase on a shared branch.
Cheat Sheet▾
| Task | Command |
|---|---|
| Rebase onto branch | git rebase main |
| Interactive cleanup | git rebase -i HEAD~N |
| Continue after fix | git rebase --continue |
| Bail out | git rebase --abort |
| Undo a public commit | git revert <hash> |
| Recover lost commits | git reflog |
Common Interview Questions▾
When should you rebase vs merge?
Rebase private/local branches to keep history linear and clean. Merge (or only ever fast-forward) shared branches. Never rebase commits others have pulled.
What does interactive rebase let you do?
Squash, reword, reorder, edit, or drop commits before sharing — to turn messy work-in-progress history into a clean, reviewable series.
You rebased and lost a commit. How do you recover it?
git reflog shows where HEAD has been; find the lost commit’s hash and
git checkout or git cherry-pick it back.