14 Mar 2024




Advanced

Let's walk through a simple example to illustrate the difference between git merge and git rebase using a common scenario of integrating changes from a feature branch into the main branch.

Imagine you have a Git repository with two branches: main and feature.

  1. Starting Point:

    main:  A --- B --- C
                  \
    feature:        D --- E
    

    Here, commits A, B, and C are on the main branch, and commits D and E are on the feature branch.

  2. Using git merge:

    Let's merge the feature branch into main:

    git checkout main
    git merge feature
    

    This results in:

    main:  A --- B --- C --- F
                  \         /
    feature:        D --- E
    

    Git creates a new commit F, known as a merge commit, to combine the changes from both branches. This merge commit has two parent commits: C (the last commit on main) and E (the last commit on feature).

  3. Using git rebase:

    Now, let's rebase the feature branch onto main:

    git checkout feature
    git rebase main
    

    This results in:

    main:  A --- B --- C
                       \
    feature:             D' --- E'
    

    Git reapplies the commits from the feature branch (D and E) on top of the latest commit of main (C). This creates new commits D' and E', which have different commit IDs because they represent the same changes but applied on top of a different base commit.

Explanation:

  • Merge: With git merge, Git creates a new commit (merge commit) that ties together the commit histories of both branches. This approach preserves the original commit history of both branches but introduces a merge commit, which explicitly indicates where the branches were merged.

  • Rebase: With git rebase, Git rewrites the commit history of the feature branch, placing its commits on top of the latest commit of the main branch. This results in a linear history with no merge commits. It's as if the work on the feature branch had been done directly on top of the latest changes in the main branch.

In summary, git merge preserves the branching structure and creates a merge commit, while git rebase rewrites the commit history to maintain a linear progression of commits. Each approach has its use cases and implications for project history and collaboration.

git
git-merge
rebase