Git Tutorial - Rebase

Jinku Hu Feb 06, 2022
  1. What Is Git Rebase?
  2. Rebase Workflow
  3. Golden Rule of Rebasing
Git Tutorial - Rebase

We’ve covered basic merges like

  • Fast-forwarded merge

  • Three-way (recursive) merge

In this tutorial, we’re going to introduce one of the most important features of Git - rebasing.

What Is Git Rebase?

Rebasing means that you’re changing the root commit of branches based on, or in other words, you’re resetting the base commit to the recent commit of the branch you’re planning to merge, like master branch.

Let’s see what this looks like,

Git Feature Branch

We have the master and Feature branches in this diagram and while we were working on our Feature branch, other team members continued to do some work on master.

We want to rebase our branch before merging it back into master and when we run the rebase command, it changes the commit that our testing branch is based on instead of pointing to C3 rather than C1. The graph below shows what happens after rebasing.

Git Feature Branch

When we merge the changes, it only has to do a fast-forward merge again because the commits are now based on the latest commit from master. This is why rebasing is one of git’s most powerful features.

After you merge this rebased Feature branch to the master, the commit log graph will be as below,

Git log graph after rebasing

It looks like the Feature branch has not ever existed and all the commit logs are in the straight line.

Rebase Workflow

  • Create the feature branch
   $ git checkout -b Feature
  • Make changes on this branch and commit
   $ git add modified.txt
   $ git commit -m 'coment here'
  • Rebase feature branch onto master
   $ git rebase master
  • Merge the rebased feature branch onto master
   $ git checkout master
   $ git merge Feature

Golden Rule of Rebasing

The golden rule is to never rebase a branch you’ve made publicly available because of the rewriting of history.

If you rebase a public branch and someone does work off that branch after you’ve rebased getting those new changes into your master branch will be very difficult because the other developers still work with the original master branch.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook