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:
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:
The graphic below shows the current active branch in Git Bash:
You can also see, as I ran this command:
It shows two files in the master branch.
Switching from master to another branch
Run the checkout command for changing from the master branch to our created branch on the local repo:
As I ran this command, see how it changed in the Git Bash:
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:
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 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:
and committed this: