Both commands combine work from two branches. They differ in what the history looks like afterwards, and in what they are safe to do.
Merge
git merge main creates a merge commit with two parents, joining the histories. Nothing existing is changed, so it is safe, and the graph shows exactly what happened and when. The downside is a history full of merge commits that can be hard to read.
Rebase
git rebase main takes the commits of your branch, sets them aside, moves the branch to the tip of main and replays your commits on top. The result is a straight line, as if you had started from the latest main. The commits are new objects with new ids, because their parent changed.
git switch feature
git fetch origin
git rebase origin/main # replay my commits on top of the latest main
git push --force-with-lease # needed because history was rewrittenThe golden rule
Never rebase commits that other people have already based work on. Rewriting shared history forces everyone to reconcile diverging copies. Rebase your own local or private feature branch freely. For shared branches, merge.
Squash merge
Many teams merge pull requests with squash, turning all the commits of a branch into one commit on main. The history of main becomes one commit per change, with a clear message, and the messy "fix typo" commits disappear.
Which to use
- Updating your feature branch with the latest
main: rebase if the branch is yours alone, merge if others share it. - Integrating a finished feature: squash merge for a tidy linear history, or a merge commit if you want to keep the branch's commits visible.
- Releases and long-lived branches: merge, to keep a true record.
Handling conflicts. Conflicts appear in both. Rebase can ask you to resolve the same conflict several times, once per replayed commit, which is one reason people squash first. If a rebase goes wrong, git rebase --abort returns you to where you started, and git reflog can recover lost commits.
Takeaway
Merge preserves history, rebase polishes it. Rebase what is private, merge what is shared, and use --force-with-lease instead of plain force when you must push rewritten history.
Comments