loading...

Git Merge vs Rebase

koshal_kkg profile image koshal garg ・1 min read

Git Merge vs Rebase

Suppose in master branch we have 2 commits "m1" and "m2" and there is a feature branch from this commit. In feature branch we have new commits "f1" and "f2" but meanwhile master has new commit "m3". These are following ways to merge feature branch to master.

Code to create initial commits

git init;
touch master.txt;

printf "m1" >>  master.txt ;
git add .;
git commit -m "m1";

printf "m2" >>  master.txt ;
git add .;
git commit -m "m2";

git checkout -b feature;
touch feature.txt;

printf "f1" >>  feature.txt ;
git add .;
git commit -m "f1";

git checkout master;
printf "m3" >>  master.txt ;
git add .;
git commit -m "m3";

git checkout feature;

printf "f2" >>  feature.txt ;
git add .;
git commit -m "f2";


# master: m1--->m2--->m3
# feature:       m2--->f1--->f2


Different ways of merging

git merge feature

git checkout master
git merge feature
# master: m1--->m2--->f1--->m3--->f2--->merge_commit

This will create a new merge commit combining all the changes in master and feature

git merge --squash feature

git checkout master
git merge --squash feature
git add .;
git commit -m "merging feature";
# master: m1--->m2--->m3--->merging feature

This will squash all changes

git rebase master

git checkout feature
git rebase master
git checkout master;
git rebase feature;
# feature: m1--->m2--->m3--->f1--->f2
# master: m1--->m2--->m3--->f1--->f2

Posted on May 25 by:

Discussion

markdown guide
 

The main difference is that in case of merges, the history is non-linear. That's why there is a marge-commit (f91729a) - it has parents in two, separate lines of development, joining them together.

> git merge feature
Merge made by the 'recursive' strategy.
 feature.txt | 2 ++
 1 file changed, 2 insertions(+)

> git log --graph --pretty=oneline --abbrev-commit
*   f91729a (HEAD -> master) Merge branch 'feature'
|\
| * 63e5ee2 (feature) f2
| * 0c2f08f f1
* | 10d563e m3
|/
* 4d6dfd0 m2
* 06f17eb m1
 

Very nice. Rebase is so much better for the history, tree and overview. Very nice overview thank you.