git rebase moves a branch's commits onto a new base — replaying your work as if it had started from a different point. The result is linear history with no merge commits, and one rule so important it is called golden.
The basic rebase #
$ git switch feature/toc
$ git rebase main
Successfully rebased and updated refs/heads/feature/toc.
Git finds the commits your branch has that main does not, and replays them one by one onto main's tip. The commits are rewritten — same changes, new hashes. That rewrite is the source of both the feature and the danger.
The golden rule #
Never rebase commits others have fetched. Once commits are on a shared remote, someone may have built on them; rewriting those commits forks history and hands every collaborator an archaeology project. Rebase your local, unpushed work freely — that is what it is for.
| Target | Rebase? |
|---|---|
| Your local, unpushed branch | Yes, freely |
| Your branch after a force-push you coordinate | With care and agreement |
| main, master, a release branch | No — merge instead |
Interactive: shaping the branch #
-i opens an editor listing the commits to replay, each with an action:
pick 9a8b7c wip: toc markup
pick b1c2d3 fix typo in toc
pick c2d3e4 toc: scroll-spy
# pick, reword, edit, squash, fixup, drop
| Action | Effect |
|---|---|
pick | Keep as-is |
reword | Keep the change, edit the message |
squash | Merge into previous commit, combine messages |
fixup | Merge into previous, discard this message |
drop | Delete the commit |
squash/fixup turn a work session into one clean commit — the legitimate use of history rewriting, done before offering the branch for merge.
Keeping a feature current #
The weekly rhythm for long-lived branches:
$ git fetch origin
$ git rebase origin/main
# conflicts? resolve, git add, then:
$ git rebase --continue # or --abort to return to the start
Each rebase replays your (few) new commits onto fresh main — conflicts stay small and attach to the commit that caused them, which is information.
Rewinding mistakes is reflog territory — a rebase that went wrong is recoverable for 90 days. The Git series continues.
