Skip to content

Instantly share code, notes, and snippets.

@nadeem-khan
Last active February 25, 2018 04:47
Show Gist options
  • Save nadeem-khan/9f691d1d894666ba595e to your computer and use it in GitHub Desktop.
Save nadeem-khan/9f691d1d894666ba595e to your computer and use it in GitHub Desktop.
When to 'git rebase' instead of 'git merge'?

git tree at default when we have not merged nor rebased:

git tree at default when we have not merged nor rebased

we get by rebasing:

we get by rebasing

So, when to 'git rebase' instead of 'git merge'?

It's simple, with rebase you say to use another branch as the new base for your work so...

If you have for example a branch master and you create a branch to implement a new feature, say you name it cool-feature, of course the master branch is the base for your new feature.

Now at a certain point you want to add the new feature you implemented in the master branch. You could just switch to master and merge the cool-feature branch:

$git checkout master
$git merge cool-feature

but this way a new dummy commit is added, if you want to avoid spaghetti-history and of course be sexier you can rebase:

$git checkout master
$git rebase cool-feature

Alternatively if you want to resolve conflicts in your topic branch as VonC suggested you can rebase you branch this way:

$git checkout cool-feature
$git rebase master

and then merge it in master:

$git checkout master
$git merge cool-feature

This time, since the topic branch has the same commits of master plus the commits with the new feature, the merge will be just a fast-forward!

What happens with the conflicts in 'git rebase' vs 'git merge'?

"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.

The reason why a rebase is then better than a merge is that:

  • You rewrite your local commit history with the one of the master (and then reapply your work, resolving any conflict then) the final merge will certainly be a "fast forward" one, because it will have all the commit history of the master, plus only your changes to reapply. Therefore the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.

  • However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment