Getting to grips with git - Part 3: rebasing

Send to friend

This is the third post in my Getting to grips with git series. In previous articles, I’ve covered the basics and merging, branching & tags. This time, I’m going to introduce the concept of rebasing. I think it justifies its own article as it’s a potentially confusing subject.

Rebasing

Rebasing is similar to merging in that it allows you to apply changes from one branch to another. Rebasing lets you replay/rewrite the history in your current branch against a particular point on another branch, so you can choose where in the history your changes appear.

For example, if say you branched from master to work on a new feature. When you branched, the state of the master branch was A, and after you’ve added some code, the state of your new feature’s branch is AB (i.e. A plus some new stuff B).

---A        master
   \
    ----AB  new feature branch

After working on your new feature for a bit, the state of the master branch might have moved on (maybe some bug fixes have been applied).

---A---------A'  master
   \
    ----AB       new feature branch

Now, to get those fixes into your new feature’s branch, you can rebase. From the new feature branch, run:

 git rebase master

This will bring the fixes into your new feature’s branch, as if you branched after the fixes were applied to master.

---A---------A'        master
             \
              ----A'B  new feature branch

A quick look at the history will confirm this.

 git log

Finally, to get your new feature into master, you can just do a merge as described in my previous blog post (from master):

git merge 

The steps I’ve just described form a common workflow. i.e.

  1. Create a new branch B from an existing branch A
  2. Make changes on new branch B
  3. Rebase updates from branch A into branch B
  4. Merge changes from branch B into branch A

Useful references on rebasing

Next time…

I still have a couple more posts planned, to cover a few more commands, git tools and forking.