Rebasing and Rewriting History
Rebase, amend, cherry-pick and history-rewriting tools all create new commits with new IDs. Use them freely on private work, carefully on anything shared, and force-push with a lease that actually protects others' commits.
Key points
- 1
Rebase replays the commits in
upstream..branchonto a new base; each replayed commit gets a new ID, and the old tip is kept in ORIG_HEAD and the reflog. - 2
git rebase --onto <newbase> <upstream> <branch>transplants just the commits inupstream..branch, which is how you move a branch off a rewritten or unwanted base. - 3
Interactive rebase lists commits oldest first:
pick,reword,edit,squash(keep both messages),fixup(drop this message),fixup -C(use this message),dropor a deleted line, andexec. - 4
During a rebase, "ours" is the branch you are rebasing onto and "theirs" is your commit being replayed: the reverse of a merge.
- 5
Rebase skips commits whose patch is already upstream, flattens merge commits unless you pass
--rebase-merges, and moves stacked branch refs only with--update-refs. - 6
Cherry-pick ranges exclude the start (
A..B); use-xto record the source, and-m 1to pick a merge commit relative to its first parent. - 7
Prefer
--force-with-leaseplus--force-if-includesover--force; a background fetch can silently satisfy a plain lease.
Common traps
A background
git fetchupdates your remote-tracking ref, so--force-with-leasecan still overwrite a teammate's commit you never saw.git checkout --ours/--theirsmean the opposite sides during a rebase compared with a merge.Rewriting history and force-pushing doesn't remove a leaked secret from clones, forks or caches: rotate the secret first.
Test yourself on Rebasing and Rewriting History
Ten questions, with the answer and explanation after each one.