DEV Community

koshal garg
koshal garg

Posted on

Git Merge vs Rebase

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

Top comments (1)

Collapse
 
nevercodealone profile image
Never Code Alone

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