Git Rebase
Git Rebase: Replaying Commits for a Clean, Linear History
git rebase moves or replays a sequence of commits from your feature branch onto a new base commit, such as the latest tip of main. While git merge keeps a branching diamond with a merge commit, git rebase produces a straight, linear commit timeline that is easy to read and bisect.
Rebasing a Feature Branch onto Updated main
gitGraph
commit id: "Base C1"
branch feature/header-nav
checkout feature/header-nav
commit id: "F1: Nav HTML"
commit id: "F2: styles.css"
checkout main
commit id: "M1: Footer fix"
commit id: "M2: Config"
When main moves ahead (M1, M2) while you build feature/header-nav, rebase your branch onto main before opening a PR:
git switch feature/header-nav
git fetch origin
git rebase origin/main
Git temporarily lifts F1 and F2, fast-forwards your branch base to origin/main, and replays F1 and F2 one by one as fresh commits (F1', F2').
Interactive Rebase (git rebase -i) to Clean Up Commits
Before sharing a feature branch for review, clean up noisy "wip" or "fix typo" commits using interactive rebase:
git rebase -i HEAD~3
Your editor opens with one line per commit. Replace pick with squash (or s) to fold a commit into the one above it, reword (r) to fix a message, or drop (d) to remove a commit completely.
Resolving Conflicts During a Rebase
If replaying a commit conflicts with changes in main, Git pauses at that specific commit. Fix the conflict markers in your file, stage it, and continue:
git add styles.css
git rebase --continue
To cancel the entire rebase and restore your branch exactly as it started, run git rebase --abort.
The Golden Rule of Rebasing
Never rebase commits on main or any public branch that other teammates are actively basing work on. Rewriting shared commit hashes forces every collaborator to untangle diverged histories.
Frequently Asked Questions
Why do I need --force-with-lease after rebasing a pushed feature branch?
Rebasing creates new commit hashes for your replayed commits, so the remote branch history diverges from your local branch. git push --force-with-lease updates your PR branch safely.
Should I pick git merge or git rebase for my team?
Many teams rebase local feature branches onto main to keep PR diffs clean, then merge the PR into main via GitHub. Pick one convention per repository and document it.
What is the difference between squash and fixup in git rebase -i?
Both combine the commit into the previous commit. squash lets you edit the combined commit message, while fixup discards the squashed commit's message automatically.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With