Middle
What is the difference between the merge and rebase commands in the Git version control system?
sobes.tech AI
Answer from AI
merge combines branches by creating a new commit with two parents, preserving the history of changes. rebase moves commits of one branch onto another, linearizing the history but changing commit hashes.
-
With
merge:- A new merge commit is created.
- The branch history remains explicit.
- Conflicts may occur, which are resolved in the new commit.
# Example of using merge git checkout feature-branch git merge main # Resolve conflicts if any git commit -m "Merge main into feature-branch" -
With
rebase:- Commits are "moved" and applied on top of the target branch.
- The history becomes linear, which may look "cleaner".
- Hashes of moved commits change.
- Conflicts may occur for each commit being rebased.
- Not recommended for branches that are already published and used by others, as it rewrites history.
# Example of using rebase git checkout feature-branch git rebase main # Resolve conflicts if any (for each conflicting commit) git add . git rebase --continue # or git rebase --skip to skip a commit # or git rebase --abort to cancel
| Feature | merge | rebase |
|---|---|---|
| History rewriting | Preserves history | Rewrites history (overwrites) |
| Commits | Creates a merge commit | Moves existing commits |
| Linear history | No (branches diverge) | Yes (simplifies history) |
| Approach | Non-destructive | Potentially destructive |
| Applicability | Public, shared branches | Local, personal branches |