Git Merging and Rebasing are two important concepts in understanding how Git works. In this tutorial, we’ll learn the difference between git merge and git rebase.
We’ll also learn the cases when we must avoid rebasing.
To follow up with this tutorial, we’ll assume:
So, the structure for us looks almost like:
To merge our feature branch into master, we’ll use:
git checkout master
git merge feature
When we merge our feature branch onto the top of the master branch, a new single commit is created in master branch having all the changes made in the feature branch across multiple commits. This new commit is referred to as a merge commit.
After performing a merge operation, our Git history would look like:
With it, we get some picture of how the entire history would look like for fairly large teams working with branching and merging across multiple branches.
At times, such a history might become a little hard to follow.
Git Rebase operation is a little hard to understand. Although it might look like just another tool to help us merging two branches, there is more to it.
To rebase feature branch onto the master, we’ll use:
git checkout feature
git rebase master
The above command will simply take each commit in the feature branch and re-apply it onto the top of the master branch.
A great advantage of using git rebase is that it helps us maintain a linear history and the graph looks like:
It is important to realize that these commits – Commit’ #3 and Commit’ #5, created on the master branch are entirely new commits with new SHA’s (commit identifier).
The changeset within each of these commits, however, remain the same as in its corresponding commit in the feature branch.
This operation of re-writing each commit in feature branch onto the top of the master is often referred to as the process of re-writing the commit history.
Therefore, git rebase is considered to be a destructive command. If used incorrectly, we might end messing up!
|Git Merge||Git Rebase|
|Merging creates an additional commit, known as merge commit, onto the target branch.||No additional commits are created while rebasing.|
|The history is graphical in nature and might look confusing and hard to follow.||The history is linear in nature, as the commits in source branch are re-applied onto the top of target branch.|
|It is a non-destructive operation.||It's a destructive operation which re-writes the commit history.|
|When in doubt, it is always safe to merge.||We should use git rebase only once we are really sure of it as it could have serious implications.|
Git documentation has clearly described the Golden Rule to remember when performing a rebase operation:
“Never use git rebase on public branches.”
So, it’s a bad idea to rebase master or any other public branch onto your local branch. It will lead to public branch diversion.
In this tutorial, we looked at git merge and git rebase operations. We also learned about the differences between them.