Rebasing & History Rewriting

💤0
Lv 10 XP
← 🧱 Foundations · Git & GitHub

Rebasing & History Rewriting

Advanced ⭐ 120 XP ⏱ 20 min #git#rebase#history

Rewrite commit history for a clean, linear log — and learn when not to.

📖Theory

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:

🌍Real-World Example
# 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
✍️Hands-On Exercise
  1. Make three small commits, then squash them into one with interactive rebase.
  2. Rebase a feature branch onto an updated main and resolve any conflict.
  3. Reword an earlier commit message using git rebase -i.
  4. Explain why you’d use git revert instead of rebase on a shared branch.
🧾Cheat Sheet
TaskCommand
Rebase onto branchgit rebase main
Interactive cleanupgit rebase -i HEAD~N
Continue after fixgit rebase --continue
Bail outgit rebase --abort
Undo a public commitgit revert <hash>
Recover lost commitsgit 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.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type