Merging and rebasing are two strategies for incorporating changes from one branch into another. Supposing two branches, master
and feature
, Git preserves the commit history of feature
on master
differently depending on the strategy you choose.
Merging gives feature work substance. Git memorializes the origin of commits from feature
and commemorates the final merge with a dedicated “merge commit”. By contrast, rebasing keeps your commit history on master
linear and therefore more searchable.
The following sequence of commands adds some commits to master
, creates a branch feature
, then merges feature
into master
. The resulting graph shows how Git preserves the work done on feature
.
echo 1 > main.txt git add main.txt git commit -m "1" echo 2 > main.txt git commit -am "2" git checkout -b feature echo 3 > feature.txt git add feature.txt git commit -m "3" git checkout - echo 4 > main.txt git commit -am "4" git merge feature --no-edit echo 5 > main.txt git commit -am "5" git log --graph --pretty=oneline --abbrev-commit * aedc5d2 5 * ca52804 Merge branch 'feature' |\ | * 05b86ef 3 * | 593c8c0 4 |/ * fb9a721 2 * cbfa685 1
The only difference in the following sequence of commands is rebasing feature
on top of master
. The resulting graph is a straight line with no mention of feature
.
echo 1 > main.txt git add main.txt git commit -m "1" echo 2 > main.txt git commit -am "2" git checkout -b feature echo 3 > feature.txt git add feature.txt git commit -m "3" git checkout - echo 4 > main.txt git commit -am "4" git rebase feature echo 5 > main.txt git commit -am "5" git log --graph --pretty=oneline --abbrev-commit * 824e964 5 * 5164ca2 4 * 4905a5f 3 * f0b3d04 2 * 2d84cee 1
Both merging and rebasing involve different workflows for resolving code conflicts and working with collaborators. Before diving into the particulars of each strategy, decide if your team prefers the searchability of rebasing or the heft of merging.
RELATED TAGS
CONTRIBUTOR
View all Courses