git merge vs rebase: which should I use?
Merge when the branch is shared, because it never rewrites commits others may have. Rebase your own local branch before sharing it, to keep history linear.
git merge main # creates a merge commit; both histories preserved
git rebase main # replays your commits on top of main; linear history#The golden rule
Never rebase commits that exist outside your machine.
Rebasing creates new commits with new hashes. If someone else has the old ones, their history and yours have diverged, and their next pull produces duplicate commits and confusing conflicts.
Rebasing your own unpushed branch is safe and often tidier.
#Merge
Pros: non-destructive, preserves exactly what happened and when branches diverged.
Cons: many merge commits make git log hard to read on a busy repository.
#Rebase
Pros: linear history that reads as a clean sequence of changes; git bisect works better on it.
Cons: rewrites history, and you may resolve the same conflict repeatedly as each commit replays.
#The common workflow
git checkout feature
git fetch origin
git rebase origin/main # tidy up locally before sharing
# resolve conflicts, then:
git rebase --continue
git push --force-with-leaseUse --force-with-lease rather than --force. It refuses to push if someone else has pushed since you last fetched, which stops you overwriting their work.
#Interactive rebase
git rebase -i HEAD~5Squash five messy work-in-progress commits into one coherent one before opening a pull request. This is the single most useful git feature most people never learn.