Git Merge and Rebase
Merge and rebase both combine work from two branches. They differ in the history they leave behind.
On this page · 5 min · Beginner
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 29, 2026
Related tutorials
Interview questions
Learning objectives#
- Merge a branch and understand fast-forward
- Rebase a feature branch onto main
- Resolve merge conflicts
- Know when not to rebase
Explanation#
git merge joins histories. If main has not moved, it fast-forwards; otherwise it creates a merge commit with two parents.
git rebase replays your commits on top of the latest main, producing a straight line of history — but it rewrites commit hashes.
Golden rule: never rebase commits that others have already pulled (shared branches). Rebase your own local work freely.
Conflicts happen when both sides changed the same lines. Edit the file, keep the right code, git add it and continue.
Code example: Updating a feature branch and resolving a conflict#
git switch feature/product-search
git fetch origin
git rebase origin/main
# CONFLICT (content): Merge conflict in src/ProductsController.cs
# Open the file, choose the correct lines between <<<<<<< ======= >>>>>>>, then:
git add src/ProductsController.cs
git rebase --continue
git push --force-with-lease # safe force-push for your own branch
# Alternative without rewriting history:
# git merge origin/main
The feature branch now sits on top of the latest main with a linear history, ready for a clean PR.
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- fetch downloads the latest main.
- rebase replays the feature commits on top of it.
- Conflicts are fixed by editing, adding and continuing.
- --force-with-lease refuses to overwrite someone else’s new commits.
Real-world use case#
Before requesting review, a developer rebases on main so reviewers see only their changes and CI tests the latest code.
Common mistakes#
Everyone else’s history breaks. Only rebase your own branches.
Can delete teammates’ commits. Use --force-with-lease.
Best practices#
- Rebase local feature branches; merge shared ones
- Pull often to keep conflicts small
- Use --force-with-lease
- Run tests after resolving conflicts
Remember this#
Merge = join histories. Rebase = replay on top.
Never rebase shared history.
Conflict: edit → add → continue.
Practice exercise#
Your task: Abort a rebase that went wrong.
Show solution
git rebase --abort
Mini quiz#
What is the golden rule of rebasing?
Want more? Practise all DevOps MCQs · DevOps interview questions
My notes#
Saved in this browser.