Creating and checking out new branches
suggest changeTo 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 that branch name exists on only one remote, and not locally, this is enough:
git checkout <branch_name>
git checkout -b <branch_name> does not do that. It always starts the new branch at the current commit. The remote-tracking form is:
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 After git branch <new_name> After git reset --hard HEAD~2
A-B-C-D-E (HEAD, master) A-B-C-D-E (HEAD, master and new_name) A-B-C (HEAD, master)
\
D-E (new_name)