ProgramGuru

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

  1. Before

    main and feature diverge.

    C ← main; D,E ← feature
  2. Rebase

    Replay feature changes on new main.

    new D', E'
  3. After

    Feature has a linear base with new commit identities.

    main → D' → E'
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~3

After 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

Why do rebased commits usually get new hashes?
Choose one answer. You can try again.

Answer and explanation

Their parent/history context changes, so they are new commit objects.

Correct.

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.

    Next lesson: Recover commits with reflog and move selected changes with cherry-pick →