Question

Suppose I have the following git tree in the beginning:

A -- B -- C -- D

I create a new branch:

git branch newbr

Then I committed one more change to master and switch to newbr

A -- B -- C -- D -- E

git checkout newbr

at this stage, I seem to have 2 ways to incorporate 'D' into newbr. 'git merge master' and 'git rebase master'. What's the difference between the two?

ps. I understand merge perfectly fine. So the question is what does 'rebased' do that's different from 'merge'?

Was it helpful?

Solution

A git rebase actually replays the current branch's commits, starting from the commit that diverged from the specified branch, on top of the specified branch. So a rebase rewrites the original history and recalculates the hashes of each commit as it applies them.So in your case newbr never diverged from master so there is nothing to do.

If, however, newbr had commits D1, D2, and D3 like this:

           D1--D2--D3 (newbr)
          /
A--B--C--D--E (master)

and then afterwards you did "git checkout newbr", then "get rebase master" git would replay D1, D2, then D3 on top of the head of master, which is at E and you would get this:

              (master)    (newbr)
             /           /
A--B--C--D--E--D1--D2--D3

So D1's parent is now different so it has a different hash as opposed to a merge which preserves the branch history. Also, notice how there is no additional merge commit when performing a rebase versus a merge. Hope this helps.

OTHER TIPS

From a high-level perspective, git merge preseves the previous commits from both branches and adds a merge commit, so you should always use it when combining two public branches. git rebase throws away one branch, rewriting it on top of the other, so you should only use it on a private branch. Since it does not add a merge commit, git rebase is slightly preferrable when pushing a previously private feature branch to a public repository.

In your case, both commands are identical since git merge would do a “fast forward” (no need for a merge commit) and git rebase would rebase zero commits. Both just have the effect of updating newbr to point to E and checking it out to the working directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top