I work with Git and frequently need to incorporate changes from other people in the branches I work on. When this happens there are those who recommend me to use git rebase
and others git merge
.
Therefore, I would like to know: what is the difference between git rebase
and git merge
?
Summary for readers eager for quick knowledge: with
git rebase
you will have a clearer history, so it is usually the preferred option.When you do
git rebase
:git pull
.This means that all your local commits appear last, after the remote commits. That is, if you do
git log
, commits from the branch you've regressed from appear as if they were older, regardless of when they were made.Suppose you have 3 commits
A
,B
,C
:Then Daniel comes along and creates a commit
D
. Then Enrique creates a commitE
:Obviously, this conflict must be resolved in some way. There are two ways to do this:
MERGE :
Both commits
D
and areE
still there, but we create a merge commitM
that inherits changes from both commitsD
andE
. However, this creates the diamond -shaped structure , which confuses many people.REBASE :
We create a commit
R
, whose content is identical to the commitM
described above. However, we load the commitE
as if it never existed (shown by the dots, on the fading line). According to this override, itE
should be a local commit of Enrique and should not have been madepush
to any repository. The advantage of this method is that the diamond shape is avoided and the history remains linear, which is something most developers appreciate.In a less visual but more descriptive way, we can refer to it as follows:
git-rebase
– Generates a series of commits sequentially, so that they can be applied directly to the head of the node.When you do a
rebase
to your branch, you're telling Git to pretend you've switched branches (checkout
) cleanly and then started working from there. This turns the changes into something clean and conceptually simple that someone else can review. You can repeat this process again when there are new changes on the other branch: you will always end up with a clean set of changes at the head of the branch.git-merge
– Join two or more development historiesWhen you un
merge
-join a branch on your own, you join the history of both. If you then do this again, you'll start to create a series of interleaved histories: some changes from Daniel, some from Harry, some from Daniel... which can be messy.Thus, speaking in silver, it is as if we were saying "we have two parents, we want a son".