Git Branching Creating and checking out new branches


To create a new branch, while staying on the current branch, use:

git branch <name>

Generally, the branch name must not contain spaces and is subject to other specifications listed here. To switch to an existing branch :

git checkout <name>

To create a new branch and switch to it:

git checkout -b <name>

To create a branch at a point other than the last commit of the current branch (also known as HEAD), use either of these commands:

git branch <name> [<start-point>]
git checkout -b <name> [<start-point>]

The <start-point> can be any revision known to git (e.g. another branch name, commit SHA, or a symbolic reference such as HEAD or a tag name):

git checkout -b <name> some_other_branch
git checkout -b <name> af295
git checkout -b <name> HEAD~5
git checkout -b <name> v1.0.5

To create a branch from a remote branch (the default <remote_name> is origin):

git branch <name> <remote_name>/<branch_name>
git checkout -b <name> <remote_name>/<branch_name>

If a given branch name is only found on one remote, you can simply use

git checkout -b <branch_name>

which is equivalent to

git checkout -b <branch_name> <remote_name>/<branch_name>

Sometimes you may need to move several of your recent commits to a new branch. This can be achieved by branching and "rolling back", like so:

git branch <new_name>
git reset --hard HEAD~2 # Go back 2 commits, you will lose uncommitted work.
git checkout <new_name>

Here is an illustrative explanation of this technique:

 Initial state       After git branch <new_name>    After git reset --hard HEAD~2
                             newBranch                        newBranch
                                 ↓                                ↓
A-B-C-D-E (HEAD)         A-B-C-D-E (HEAD)                 A-B-C-D-E (HEAD)
        ↑                        ↑                            ↑
      master                   master                       master