Differences Between merge and rebase
1. merge
- Purpose: Merge the histories of two branches, creating a new merge commit.
- Advantages:
- Preserves the branch history and branching structure.
- Simple to operate, suitable for team collaboration.
- Disadvantages:
- History may contain extra merge commits, making logs more complex.
Example:
A---B---C---D (master)
\
E---F (feature)
After executing git merge feature:
A---B---C---D---G (master)
\ /
E-------F (feature)
G is the merge commit.
2. rebase
- Purpose: “Move” the commits of the current branch onto the latest commit of the target branch, rewriting the commit history.
- Advantages:
- Makes commit history more linear and tidy.
- Easier to understand each change.
- Disadvantages:
- Rewrites history (commit hashes change), not suitable for public branches already pushed to remote.
- Improper use may cause conflicts that are difficult to resolve.
Example:
A---B---C---D (master)
\
E---F (feature)
After executing git rebase master:
A---B---C---D---E'---F' (feature)
E’ and F’ are new commits based on D.
3. Recommendations
- merge: Suitable for team collaboration, preserves branch history.
- rebase: Suitable for individual development or cleaning up commits, keeps history tidy.
4. Common Commands
-
Merge branch:
git checkout master git merge feature -
Rebase branch:
git checkout feature git rebase master
5. Summary
| Operation | Rewrite History? | Create Merge Commit? | History Structure | Recommended Scenario |
|---|---|---|---|---|
| merge | No | Yes | Branch + Merge | Team Collaboration |
| rebase | Yes | No | Linear | Personal Cleanup/Small Team |
Note: Do not perform rebase on public branches already pushed to remote!