Differences between git merge and git rebase

Merging and rebasing are the two most popular way to applying changes from one branch into another one. They both give you the same result at the end, so let’s talk about differences.

Briefly:

  • git merge apply all unique commits from branch A into branch B in one commit with final result
  • git merge doesn’t rewrite commit history, just adds one new commit
  • git rebase gets all unique commits from both branches and applies them one by one
  • git rebase rewrites commit history but doesn’t create extra commit for merging

Detailed:

Default git strategy for merging is simple three-way merging. It means that Git uses the two snapshots (every commit has snapshot for full working directory) pointed to by the branch tips and the common ancestor of the two and then make result commit with applied changes from both branches.

Example from PRO Git:

Git rebase going to the common ancestor of the two branches (the one you’re on and the one you’re rebasing onto), getting the diff introduced by each commit of the branch you’re on, saving those diffs to temporary files, resetting the current branch to the same commit as the branch you are rebasing onto, and finally applying each change in turn.

Example from PRO Git:

When to use:

  • git merge is a default behavior when you use git pull. Use it as default if you are not bothering about commit history and want to avoid problems
  • use git rebase to make your commit history more clear and consistent (use it only before pushing to remote servers to keep your name and karma clean)
  • use git rebase for temporary local branches — they are not necessary for public commit history and won’t make problems
  • use git rebase -i (interactive) for rewriting your local commit history into pretty one before pushing it on the remote server.
Like what you read? Give Volodymyr Dmytrechko a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.