git rebase vs git merge: When to Use Each
Both merge and rebase combine work from two branches. They differ in the history they produce.
Merge: preserve history as it happened
git switch feature/search
git merge main # creates a merge commit joining both histories
Safe and non-destructive, but frequent merges from main create a tangled graph.
Rebase: replay your commits on top
git switch feature/search
git rebase main # your commits are re-created after main's latest commit
The result is a straight line, as if you'd started your work from the latest main. Your commits get new IDs because they're new commits.
The golden rule
Don't rebase commits that others have based work on. Rebasing your own local or personal feature branch is fine. Rebasing a shared branch rewrites history under your teammates' feet. If you've already pushed your own branch, update it with git push --force-with-lease, which refuses to overwrite commits you haven't seen.
Interactive rebase: tidy up before review
git rebase -i main
pick 3f2a1c4 Add search endpoint
fixup 9b8e7d6 typo
pick 1a2b3c4 Add search UI
reword 5d6e7f8 wip
drop 7f8e9d0 debug logging
fixup/squash- fold a commit into the previous one.reword- change the message.drop- remove the commit.- Reorder lines to reorder commits.
Tip: commit fixes with git commit --fixup <sha>, then run git rebase -i --autosquash main to fold them in automatically.
Team conventions
- Rebase your feature branch on
mainto stay current; merge (or squash-merge) the pull request intomain. - If a rebase goes wrong:
git rebase --abort, or find the old state ingit reflog.
Comments
No comments yet. Have a question or a tip? Be the first to share it.