Rebase local work and clean up history
Rebase local work and clean up history
Merge preserves the branch structure. Rebase can replay your local commits on a different base, producing a linear-looking history. Both are useful; neither is universally better.
What you’ll learn
- Explain merge versus rebase.
- Run a basic rebase.
- Recognize when history rewriting is unsafe.
Replay a topic branch
Before
main and feature diverge.
C ← main; D,E ← featureRebase
Replay feature changes on new main.
new D', E'After
Feature has a linear base with new commit identities.
main → D' → E'
Rebase rewrites commit identity
git rebase main finds commits unique to your current branch and reapplies their changes on top of main. The replayed commits receive new identities because their parent history changed.
git rebase -i can reorder, reword, squash or edit local commits. This is valuable before sharing a branch, but rewriting commits that teammates already based work on can create duplicate histories and confusion.
Replay a feature on the latest main
Run this in a disposable practice repository unless the lesson explicitly says otherwise.
git switch feature/search
git fetch origin
git rebase origin/main
# before publishing local cleanup
git rebase -i HEAD~3After a successful rebase, the feature commits appear after origin/main with new hashes. If conflicts occur, resolve them, stage files and run git rebase --continue; git rebase --abort returns to the pre-rebase state.
Practice: Rebase and history rewriting
Your task: In a disposable repository, create two feature commits and one new main commit. Draw the graph before rebase, run rebase, then draw the new graph and note the changed feature hashes.
Common pitfall to avoid
The safest beginner rule is: freely rewrite commits that are only yours and not yet shared; coordinate carefully before rewriting commits others may have pulled.
Check your understanding
Rebase and history rewriting: what to remember
Rebase local work and clean up history is complete when you can explain the state being changed before you run the command, not merely repeat the syntax.
Read further: official supporting documentation.
Reaching the recap and completing the quizzes are separate milestones.