← Learning Hub
Advanced

Rebase and a Clean History

git rebase moves your branch's commits so they start from the latest main, as if you had begun your work today. The result is a straight, easy-to-read history without extra merge commits.

Rebase replays your commits on top of the latest main, giving a straight, tidy history instead of many merge commits. It rewrites commit history, so it's great for your own branches but must not be used on branches others are already using.

Example
git switch feature-search
git fetch origin
git rebase origin/main
# Successfully rebased and updated refs/heads/feature-search.

If a conflict appears during a rebase, fix the file, git add it, and run git rebase --continue. To give up: git rebase --abort.

Interactive rebase: tidy up before a PR

Example
git rebase -i HEAD~3
# pick   a1b2c3d Add search box
# squash d4e5f6a fix typo
# reword 9f8e7d6 wip
  • pick - keep the commit
  • squash / fixup - melt it into the commit above
  • reword - change its message
  • drop - remove it

The golden rule

Never rebase commits that others already have (for example, on a shared main). Rebase rewrites commits with new ids; teammates' copies would no longer match. Rebase only your own unshared branches.

Example
# After rebasing a branch you had already pushed (your own PR branch only):
git push --force-with-lease
--force-with-lease refuses to overwrite the remote if someone else pushed in the meantime. Prefer it over plain --force.
Key points
  • git rebase main moves your commits onto the latest main.
  • Interactive rebase can squash and reorder commits.
  • Don't rebase branches others share.

📝 Test yourself

1. What does rebasing onto main do?
2. Which commits should you never rebase?
3. Fill in the safer force-push option:
git push --