Rewriting History
Rebase rewrites commit history to create a cleaner, more linear timeline. It's one of Git's most powerful tools—and one that requires caution.
Basic Rebase
# From your feature branch
git rebase mainThis replays your commits on top of main, as if you had started your feature from the latest main commit.
Rebase vs Merge
- Merge: Preserves history exactly as it happened and creates a merge commit
- Rebase: Creates a linear history by rewriting your commits onto a new base
Interactive Rebase
git rebase -i HEAD~3Opens an editor to modify your last three commits. Available actions:
pick: Keep the commit as-isreword: Change the commit messageedit: Pause to modify the commit's changessquash: Combine with the previous commitdrop: Remove the commit entirely
Squashing Commits
Combine several small commits into one meaningful one:
git rebase -i HEAD~3Then change the plan to:
pick abc123 Add sensor calibration
squash def456 Fix typo
squash ghi789 Fix another typo
Resolving Rebase Conflicts
- Fix the conflicts in the affected files
- Stage the resolved files with
git add - Continue with
git rebase --continue
Aborting a Rebase
git rebase --abortReturns your branch to its state before the rebase began.
The Golden Rule
Never Rebase Public Commits
Don't rebase commits that have been pushed to shared branches. Doing so rewrites history that others depend on and causes chaos across the crew.
Rebase is safe for:
- Local commits you haven't pushed yet
- Personal feature branches
- Cleaning up your history before opening a pull request
When to Use Rebase
- Clean up messy local commits before sharing them
- Keep a feature branch up to date with
main - Create a linear history that's easier to read
When to Use Merge
- Shared or public branches
- You want to preserve the full context of how work happened
- Your team prefers explicit merge commits
Handy Rebase Options
git rebase --onto main old-base feature # Replay onto a different base
git rebase --autostash main # Stash, rebase, then restore local changes
git pull --rebase # Rebase instead of merge when pulling--autostash is a small quality-of-life win: no more manual git stash before every rebase.
Next: Selective Updates
Rebase replays whole branches, but sometimes you only need one commit. Next, learn git cherry-pick—applying individual commits wherever you need them.