Home > git > git branching by example

git branching by example

In this post I am going to demonstrate how to use git to apply a bug fix from the master branch to a feature branch that has already committed a new feature.

Example: fork a branch, add some new features to it. In the meanwhile add a bug fix to the master branch. We want to apply the bug fix to the feature branch while working on it but we decide it’s not time yet to add the new feature to the master branch. The simplest way I found (so far) is to create a temporary branch (and switch to it) on top of the master branch with the bug-fix commit, merge from feature branch, then switch to feature branch, merge changes from combined.

mkdir demo_proj
cd demo_proj
vi func.php

Put the following code into func.php and save.

    function do_something() {
        echo "hello\n";
        return "wrong value";
git add .
git commit -a -m "added function do_something in func.php"
git checkout -b feature
vi func.php

Add a new function new_feature() to func.php

    function do_something() {
        echo "hello\n";
        return "wrong value";

    function new_feature() {
        return 999;
git checkout master
vi func.php

Change word “wrong” to “right”:

	function do_something() {
		echo "hello\n";
		return "right value";
git commit -a -m "fixed a bug in do_something()"
git checkout -b combined
git merge feature
git checkout feature
git merge combined
git branch -d combined

After “git merge combined” the feature branch has the bug-fix from master branch while maintaining its own new_feature() function. Branch combined has accomplished its goal hence it’s OK to remove it.

Categories: git
  1. December 21, 2011 at 2:02 pm

    The approach you describe will also merge all recent commits to ‘master’ into the ‘feature’ branch, which may or may not be what is desired. For example, one certainly wouldn’t want to merge ‘master’ into a ‘release’ branch, though it may be desirable to pull in a bugfix patch.

    You can do that by running ‘git cherry-pick’ while the ‘feature’ branch is checked out, giving the name of the commit that fixes the bug as the argument.

    • ricoch3n
      December 21, 2011 at 7:08 pm

      Actually cherry-pick is a better solution, thanks for pointing that out.

  2. December 30, 2011 at 12:34 pm

    There may be noticeably a bundle to learn about this. I assume you made sure nice points in options also.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: