How to switch branch in Git?

git checkout command is used to change branch. Switching a branch is also known as checking out a branch. There are two ways you can use git checkout:

  1. Using git checkout command to change branch.
  2. Using git checkout command to create a new branch and switch to that new branch.

How to change branch using git checkout?

You pass the branch name to which you want to switch to git checkout

Before running the command, ensure that you have already created that branch. You can list all the branches using git branch.

$git branch
* master
  testing

You can see that the testing branch is already created, so you can change to it easily.

$git checkout testing
Switched to branch 'testing'

You can view the currently active branch by typing git branch:

$git branch
* testing
  master

Now, you can see that the active branch is testing.

How to create and switch the newly created branch?

When you specify -b option to git checkout, two things happen:

  1. A new branch is created.
  2. You are switched to that newly created branch.

Let's understand the entire concept with the help of an example:

$git branch
* master

You can see that there is no testing branch. Let's create a testing branch and check it out in a single command.

$git checkout -b testing
$git branch
* testing
  master

Now, you can see that the testing branch is created and it is the currently checked out branch.