git,

Git: merge vs rebase

Oct 26, 2022 · 2 mins read · Post a comment

Probably the most searched Git comparison ever made between merge and rebase. The most debated as well in terms of use case and a popular DevOps interview question as well. I’m going to try to break them down as simple as I can, but overall it comes down to what you want your Git history to look like.

Prerequisites

  • Git

Solution

git merge

The merge operation is basically a commit that takes changes from one branch and merges them into another. Simple as that.

Commonly used when developing new features covering most if not all chiefly known branching strategies as they are following the branch-per-feature model. Each branch representing a new feature where once developed will be merged back to the base branch being main or master.

To merge the abc-feature branch to main, run:

git checkout main
git fetch && git pull
git merge abc-feature

Pros:

  • Preserves the Git history.

Cons:

  • Clumsy logs, not so easy to navigate.

git rebase

The rebase operation moves all commits from the current branch onto a new base commit. A base commit is the initial commit that branches are created from.

To rebase changes on abc-feature branch from main, run:

git checkout abc-feature
git fetch && git pull
git rebase main
git checkout main
git merge abc-feature

Note(s):

  • git rebase main updates abc-feature’s base commit to point to main.
  • Merging after rebase is required since the rebase involves “moving” of commits. At the end of the day, you still need to merge before pushing to remote.

Related: Git: restore vs reset vs revert vs rebase.

Pros:

  • Git logs are linear. Easy to navigate.
  • Prevent bugs and spares you from resolving conflicts and a possible rework.

Cons:

  • You cannot track how and when the commits were merged hence Git history not being preserved at all.

the diff

  • merge a single commit where rebase involves whatever number of commits are being included in the current branch.
  • merge creates a merge-commit. rebase only “relocate” commits.
  • merge preserves history as rebase does not.

Conclusion

In case of doubt, use merge. In fact, always use merge. The Git history could look as clumsy as it could get, but at least it’s preserved. And that’s the hill I’m willing to die on.

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git