Create a New Branch in Git
New to Git? We've all been there when even the simplest thing seems complicated.
It's okay not to know or remember things. This is why tutorials like this exist to help you out.
If you want to create a new local branch in Git, use the git branch
command:
git branch <BRANCH-NAME>
But git branch
is not the only command for this purpose. You may also git checkout -b
to create a new local branch and then switch to it.
Let's have a look at these commands in detail.
Method 1: Create a new local branch with git branch command
This is what I recommend using because it is easier to relate and remember.
git branch <BRANCH-NAME>
Let's go over the practical usage and behavior of git branch
command.
$ git branch
* master
$ git branch new-lhb-branch
$ git branch
* master
new-lhb-branch
As you can see, a new local Git branch new-lhb-branch
is created. But, the active branch is still the master
branch. To switch to this newly created branch, you can use git switch
command:
git switch <BRANCH-NAME>
Method 2: Creating a new branch with git checkout -b command
And now, let's look at the syntax for 'git checkout' command:
git checkout -b <BRANCH-NAME>
The -b
flag is to run git branch
before running git checkout
.
Let's go over an example for the git checkout
command as well...
$ git branch
* master
$ git checkout -b new-branch-lhb
Switched to a new branch 'new-branch-lhb'
$ git branch
master
* new-branch-lhb
As you can see now, the git checkout
command did not only create a new branch but also switched to the newly created branch.
Difference between git branch and git checkout -b
The main difference between using the git branch
command the git checkout
command along with -b
flag is that when you use git branch
command, it will only create a new local branch. Whereas, if you use git checkout
command with the -b
flag, it will create a new local branch and immediately switch to the newly created branch.
Now that you have learned about creating branches in Git, you should also learn about deleting them.