Git – Difference between merge and rebase

Let’s go back to basics: Git.

This powerful versioning tool is hugely underestimated by newcomers because “Oh jeez it’s so hard to understand what’s the difference between git pull origin master and git merge origin/master, and what the hell is this slash in the middle“?

Yeah, just trolling, but actually there’s something awesome we can do and that’s very simple “in the end”: rebasing.

Start from here.

We will work on branch second_branch, which is created based on a previous version of the master branch. The second_branch has one commit more than master. But, between now and when I created the branch, someone commited on master.

Our branches diverge.

Problem: I need the modifications from Commit 3 to work on my branch (or my lead developer wants me to always keep my working directory up to date with the master).

Two possibilities here:

  • Use merge (or pull for the lazy ones).
  • Use rebase.

Reminder: we work on second_branch. It means we previously ran a git checkout second_branch command.

Summary

git merge {branch}
Applies modifications of the {branch} branch to the current branch, and if branches diverge (or --no-ff is specified), it will create a new “merge commit” indicating that the two branches were merged.
rebase {branch}
Rewrites the current branch history . At first, it keeps all “new commits” of the current branch (starting from head) in memory, then applies all “missing” commits from the {branch} (which should inexorably fast-forward), and finally applies all kept-in-memory commits’ modifications from the current branch, one-by-one, until every conflict (if there are some) is resolved, and changes the new commits’ hashes.

And rebasing is just one component of Git.
Just look at for-each-ref command, or even log, you can do beautiful things with them!

Leave a Reply