14 Mar 2024
Let's walk through a simple example to illustrate the difference between git merge and git rebase using a common scenario of integrating changes from a feature branch into the main branch.
Imagine you have a Git repository with two branches: main and feature.
-
Starting Point:
main: A --- B --- C \ feature: D --- EHere, commits
A,B, andCare on themainbranch, and commitsDandEare on thefeaturebranch. -
Using
git merge:Let's merge the
featurebranch intomain:git checkout main git merge featureThis results in:
main: A --- B --- C --- F \ / feature: D --- EGit creates a new commit
F, known as a merge commit, to combine the changes from both branches. This merge commit has two parent commits:C(the last commit onmain) andE(the last commit onfeature). -
Using
git rebase:Now, let's rebase the
featurebranch ontomain:git checkout feature git rebase mainThis results in:
main: A --- B --- C \ feature: D' --- E'Git reapplies the commits from the
featurebranch (DandE) on top of the latest commit ofmain(C). This creates new commitsD'andE', which have different commit IDs because they represent the same changes but applied on top of a different base commit.
Explanation:
-
Merge: With
git merge, Git creates a new commit (merge commit) that ties together the commit histories of both branches. This approach preserves the original commit history of both branches but introduces a merge commit, which explicitly indicates where the branches were merged. -
Rebase: With
git rebase, Git rewrites the commit history of the feature branch, placing its commits on top of the latest commit of the main branch. This results in a linear history with no merge commits. It's as if the work on the feature branch had been done directly on top of the latest changes in the main branch.
In summary, git merge preserves the branching structure and creates a merge commit, while git rebase rewrites the commit history to maintain a linear progression of commits. Each approach has its use cases and implications for project history and collaboration.