DEV Community

Amaresh Pelleti
Amaresh Pelleti

Posted on Originally published at devtoolhub.com

Git Rebase vs Merge: What Changes, Tested on Git 2.56

Git merge joins two histories and adds a merge commit, leaving every existing commit untouched. Git rebase replays your commits on top of another branch, so they get new SHAs and the history becomes a straight line. I ran both on Git 2.56.0 in throwaway repositories. Here is what each one did.

Merge keeps commits, rebase rewrites them

With a three-commit feature branch and two new commits on main:

git merge feature
# * d177a82 Merge feature        (two parents)
# |\
# | * 4aa3fb4 feature 3          (same SHAs as before)
Enter fullscreen mode Exit fullscreen mode
git rebase main
# * d52c022 feature 3            (was 44151c4)
# * 3404667 feature 2            (was 8cab062)
# * a74e8a3 feature 1            (was 6af63b4)
Enter fullscreen mode Exit fullscreen mode

Rebase kept the changes and messages but made new commits, because a commit's SHA depends on its parent.

Conflicts and force pushes

One conflict spanning two of the three feature commits was resolved once in a merge and twice in a rebase, because rebase replays commits one at a time.

After rebasing a pushed branch, a plain git push was rejected as non-fast-forward. When a teammate had pushed in the meantime, git push --force-with-lease refused with stale info, while plain git push --force succeeded and removed their commit from the branch.

Squash, revert and undo

  • git merge --squash leaves one commit, but git branch -d feature then fails with not fully merged.
  • Reverting a merge commit needs git revert -m 1.
  • git reset --hard ORIG_HEAD undid a finished rebase.

What I did not test

Interactive rebase, --autosquash, rerere, the pull.rebase config, GitHub's Rebase and merge button, Windows and large histories.

My rule: rebase what only you have, merge what others share. The full post, with every command, the pull behavior, --rebase-merges and an FAQ, is on DevToolHub.

Top comments (0)