How to switch branches in Git?

If you have multiple branches in your repository then switching from one branch to another is easy.

For changing one branch to another use the checkout command as described below.

Suppose we have a master and hello-git-branch in our repo. The current branch is master and we require switching to the hello-git-branch. Run this command for switching:

$ git checkout hello-git-branch

This command should result in switching from the current branch to hello-git-branch. Now you may start adding, committing, or performing other operations in that branch.

An example of changing the current branch in Git Bash

Let us now go through switching branches in our local repository. For the demo, I have transferred a remote repo (from the Github website) to the local machine.

The repo contains two branches:

  • Master branch
  • The other branch is created by using the following command:
$ git branch hello-git-branch

The graphic below shows the current active branch in Git Bash:

Git switch branch

You can also see, as I ran this command:

$ ls

It shows two files in the master branch.

Did you know? Do not mix up the git checkout with the git clone command if you have SVN/CVS background. As such, SVN/CVS used a clone command for switching the branches. In Git, the clone command is used to fetch code from the remote repository.

Switching from master to another branch

Run the checkout command for changing from the master branch to our created branch on the local repo:

$ git checkout hello-git-branch

As I ran this command, see how it changed in the Git Bash:

Git change branch local

You can see that no message is displayed, however, in brackets, the hello-git-branch is displayed.

Now, any work you do is associated with the hello-git-branch. For example, listing the files by running the following command:

$ ls

See which files are listed now as compared to when we were on the master branch:

Git checkout branch

You can see this branch contains three files while the master branch shows only two files. The reason is I added a file file-2.txt in hello-git-branch by using add command as follows:

$ git add file-2.txt

and committed this:

$ git commit –m “add new file in branch”
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!