Git 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, some people 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 off 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.