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 perform other operations in that branch.
The example of changing 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 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:
You can also see, as I ran this command:
$ ls
It is showing two files in the master branch.
Switching from master to another branch
Run the checkout command for changing from master branch to our created branch on local repo:
$ git checkout hello-git-branch
As I ran this command, see how it changed in the Git Bash:
You can see, 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, as 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:
You can see this branch contains three files while master branch is showing 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”