git rebase — Rewriting and Linearizing History
Mastering git rebase: standard rebase, interactive rebase (squash, reword, drop, edit), and the Golden Rule of Rebasing.
git rebase — Rewriting and Linearizing History
git rebase moves or reapplies a sequence of commits to a new base commit. Rebasing produces a completely linear, chronological commit history without cluttering your graph with unnecessary 3-way merge commits.
1. How Rebase Works
Before Rebase:
main ────► [C1] ──► [C2] ──► [C3]
│
└──► [C4] ──► [C5] (feature)
After 'git rebase main' on feature branch:
main ────► [C1] ──► [C2] ──► [C3] ──► [C4'] ──► [C5'] (feature)Git temporarily removes your feature branch commits (C4, C5), fast-forwards your branch to the tip of main (C3), and then reapplies your commits one by one on top of C3.
2. Interactive Rebase (git rebase -i)
Interactive rebasing allows you to clean up, squash, reorder, or rename local commits before opening a pull request:
git rebase -i HEAD~3Git opens your editor with a list of commits:
pick 7a8b901 feat: add user model
pick 4c2d189 fix: typo in model name
pick 9e0f312 test: add model validation tests
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# s, squash = meld into previous commit
# d, drop = remove commitChange the second line from pick to squash to merge the typo fix directly into the feature commit!
3. The Golden Rule of Rebasing
Related Topics
git merge — Combining Branch Histories
How to merge branches in Git: Fast-Forward merges, 3-way merge commits (--no-ff), squash merging (--squash), and resolving divergence.
git stash — Temporarily Shelving Changes
How to stash uncommitted changes: git stash save, git stash pop, stashing untracked files (-u), viewing stash lists, and dropping stashes.