Git merge vs rebase; What’s the difference?

Git merge and rebase are two very useful commands to work with git branching. In this article, we will discuss the difference between these commands.

Git merge

Git merge command joins two or more development histories together. We will denote git commits using the letter C and the main branch name as main. Let’s start with the main branch, it has two commits C0 and C1.The asterisk symbol(*) denotes git HEAD position (main*) as shown below.

Create a feature branch “feature” and add two commits(C2, C3).

The main branch updated with commits C4, C5, C6.

Finally, we need to bring those changes in the feature branch to the main branch. For merging, we can use the git merge command. First, make sure that we are in the main branch. Git checkout /git switch command used to switch branches.

git checkout main
git switch main
git merge newfeature

After running the git merge command we can see branches with commits as shown below.

After merging we can see commit history is diverted here and added a new merge commit C7.This is a simple three-way merge, using the two snapshots pointed to by the branch tips and the common ancestor of the two.

Git rebase

Let us now check the git rebase command. Rebase command reapplies commits on top of another base tip. In other words, rebasing means you can take the patch of the change that was introduced in C2 and C3 and reapply it on top of C6. We have the main branch and a feature branch with commits as shown below

Ensure that we are in the feature branch and run the git rebase command.

git checkout feature
git switch feature
git reabse main

From the above diagram after rebasing, we can see that the C2 and C3 commit of the feature branch moved to the main branch’s top as C2′ and C3′ thus commit history is clean, and no extra merge commit.

In conclusion, to integrate changes from one branch into another we can use git merge, rebase commands. Git rebase helps keep to commit history clean, it also eliminates unnecessary merge commits required by git merge.

Leave a Comment