Sub topic 14
Merge or rebase: choosing and avoiding pitfalls
This chapter assumes you can create branches, run git merge, and have seen git rebase replay commits. Here you decide which one to use and avoid the errors that rebasing causes.
What each command does to history
Both commands combine work from two branches. They differ in the history they leave behind.
- Merge keeps both lines of work as they happened. When the branches have diverged, Git adds a merge commit with two parents. Existing commits are unchanged.
- Rebase copies your commits onto a new base. The copies have new hashes, and the originals are abandoned. The result is a straight line.
The golden rule
Never rebase commits that other people already have. Rebasing changes commit hashes. If a teammate based work on the old commits, their history and yours no longer match. Git then shows duplicated commits and conflicts that were already resolved.
Rebasing a branch only you use is safe, even if you pushed it, as long as you tell anyone else using it.
Choosing
| Situation | Prefer |
|---|---|
| Updating your private feature branch with the latest `main` | Rebase |
| Cleaning up your own commits before review | Rebase |
| Bringing a finished feature into `main` | Merge |
| The branch is shared or already used by others | Merge |
| You want a record that a feature branch existed | Merge with `--no-ff` |
Many teams combine them. They rebase a private branch onto main to stay current, then merge it into main when the work is done.
Worked example
You are on feature/login, and main has moved on. To bring in the new work:
git fetch origin
git rebase origin/mainIf a commit conflicts, Git pauses. Fix the file, then continue:
git add path/to/conflicted-file
git rebase --continueTo give up and return to where you started, run git rebase --abort. Then publish the rewritten branch:
git push --force-with-leaseCompare this with a merge, which would run git merge origin/main and add one merge commit. With a merge you resolve conflicts once. With a rebase you may resolve them once per replayed commit.
Common mistakes
- Rebasing
mainor another shared branch. This rewrites history others depend on. Rebase your own branch onto the shared one, never the reverse. - Using
--forceinstead of--force-with-lease. You can silently delete a teammate's pushed commits. - Panicking after a bad rebase. The old commits still exist. Find the pre-rebase state with
git reflogand reset the branch to it. - Resolving the same conflict repeatedly. If a long branch conflicts at every commit, merge instead.
Exercise
You pushed feature/search and a teammate pulled it and added commits. You now want to bring in the latest main. Should you rebase or merge, and why?
Show answer
Merge. The branch is shared, and rebasing would rewrite commits your teammate already has, which causes duplicated commits and conflicts for them. Run git merge origin/main on the branch instead.