Git Merge vs. Rebase


Git merge and rebase are two different approaches to combining changes from one branch into another.

1. Git Merge

When you perform a merge, Git creates a new commit that incorporates the changes from the source branch into the target branch. This results in a merge commit that has two or more parent commits. Here’s an example:

Suppose you have a feature branch called feature_branch and you want to merge it into the main branch. You would run the following commands:

Terminal
git checkout main
git merge feature_branch

Here, Git will create a new merge commit that combines the changes from feature_branch into main. The merge commit will have two parents: the latest commit on main and the latest commit on feature_branch. This approach preserves the commit history of both branches.

Post you make like: Git Top Daily Life Usage Commands

2. Git Rebase

Rebase, on the other hand, moves or reapplies commits from one branch onto another. It effectively changes the base of the branch to the commit where the rebase is being applied. This results in a linear commit history without merge commits. Here’s an example:

Let’s consider the same scenario as before, where you have the feature_branch and want to incorporate its changes into main. Instead of merging, you would run the following commands:

Terminal
git checkout feature_branch
git rebase main

Here, Git will replay the commits from feature_branch on top of main, effectively moving the entire branch. This creates new commits with different commit IDs but the same changes. The commit history appears as if the work on feature_branch happened directly on top of main.

Summary

The context and project requirements determine whether to merge or rebase. The major purpose of merge is to incorporate changes from feature branches into the main branch while maintaining the branch history. Rebase is helpful when you want to have a clear, linear commit history without merge commits, but you should use it carefully when working on shared branches to prevent altering history that other people could depend on.

References

  1. Git Merge- Official Doc
  2. Git Rebase- Official Doc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.