How to create branches in Git?

When you run git init, Git creates a master branch for you. The master branch is always deployed to customers. So, it is advised to create a separate branch where you thoroughly test the code and when that code is ready to share merge it with the master branch. This tutorial will show you the process of creating branches.

There are two ways of creating branches in Git:

  1. Using git branch command
  2. Using git checkout command

Note: "creating branches" or "creating new branches" is the same thing.

How to create branches using git branch command?

To create a branch, you type git branch branch-name

branch-name is the name of the branch that you want to have. It is recommended that the branch name should be in lowercase. And if a branch name has multiple words then separate them by dashes.

Suppose you want to create a testing branch then type the following command:

$git branch testing

You can view all the branches by running git branch command without the branch name.

$git branch
* master
  testing

How to create branches using git checkout command?

Usually, git checkout command is used to switch a branch. But when you pass -b option to git checkout, it creates a branch before checking it out.

Suppose, you want to create a production branch and switch to it all in one step then run the following command:

$git checkout -b production

It will create a production branch and switch you to this branch which you can verify by running git branch:

$git branch
* production
  master