What is the difference between git merge and git rebase?
- Technology:
- Git
- Roles:
- Frontend Developer,
- Backend Developer,
- Full Stack Developer,
- Software Engineer,
- DevOps Engineer,
- QA Engineer,
- Mobile Developer,
- Data Engineer,
- Machine Learning Engineer
- Topics:
- Git
Quick answer
Both integrate changes from one branch into another: merge keeps both histories and joins them with a merge commit, while rebase rewrites your commits so they appear on top of the target branch, giving a linear history.
Detailed explanation
Merging main into a feature branch creates a merge commit with two parents. Nothing is rewritten, so it is safe on shared branches, and the history shows exactly when branches were combined. The cost is a busier history with many merge commits.
Rebasing a feature branch onto main takes each of your commits and replays it on the latest main, creating new commits with new hashes. The result reads as if you started your work from the current main, which makes git log and git bisect easier to follow.
Because rebase rewrites history, the golden rule is: never rebase commits that other people have already based work on. Rebase your private feature branch to tidy it up, then merge it (often with a squash or fast-forward) into the shared branch.
Example
# merge: keeps history, adds a merge commit
git switch feature
git merge main
# rebase: replays feature commits on top of main
git switch feature
git rebase main
git push --force-with-lease # needed because hashes changedHow to explain it in an interview
Merge combines two branches with a merge commit and never rewrites history, so it is safe on shared branches. Rebase replays my commits on top of the target branch, which gives a clean linear history but changes commit hashes. I rebase my own feature branch to keep it current and tidy, and I never rebase a branch someone else is working on.
Key points
- Merge preserves history and is safe on shared branches
- Rebase rewrites commits to produce a linear history
- Never rebase commits that others already use
- Use --force-with-lease, not --force, after rebasing
Common mistakes
- Rebasing a shared branch and force-pushing, which breaks teammates who pulled the old commits.
- Using git push --force instead of --force-with-lease, which can silently overwrite someone else鈥檚 push.
- Claiming rebase avoids conflicts. You may resolve the same conflict once per replayed commit.
Follow-up questions
- How do you resolve a merge conflict in Git?
- What is an interactive rebase used for?