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.
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
git rebase -i HEAD~3
# pick a1b2c3d Add search box
# squash d4e5f6a fix typo
# reword 9f8e7d6 wippick- keep the commitsquash/fixup- melt it into the commit abovereword- change its messagedrop- 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.
# 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.- git rebase main moves your commits onto the latest main.
- Interactive rebase can squash and reorder commits.
- Don't rebase branches others share.
