Junior — Middle
What is the difference between 'git merge' and 'git rebase' when combining branches in the Git version control system?
sobes.tech AI
Answer from AI
The git merge and git rebase commands are both used to combine changes from one branch into another, but they do so differently:
-
git merge creates a new merge commit that combines the history of both branches, preserving their parallel history.
- Example:
git checkout master git merge feature-branch - The branch history remains branched, showing when and which branches were merged.
- Example:
-
git rebase re-applies (rewrites) commits from one branch onto another, creating a linear history without merge commits.
- Example:
git checkout feature-branch git rebase master - It’s like starting the branch anew from the last commit of master, simplifying history but changing commit hashes.
- Example:
When to use:
mergeis convenient for preserving full history and when branch transparency is important.rebaseis useful for simplifying history before merging into the main branch, to avoid unnecessary merge commits.
It’s important to remember that rebase rewrites history, so it’s not recommended to rebase public branches that are already shared with others.