How to Switch Branch on Git
We will create a new branch whenever we have to try something new with our project. Branches provide us with an independent environment where we can work without worrying about affecting the rest of the project.
These branches can then be merged with our master branch or some other feature branch. A repository can have multiple branches and, we must know how to switch between these branches. Let's learn how to switch branches in Git.
Git provides us the Git Checkout and Git Switch commands to navigate to different branches. Git Checkout is capable of a lot more but the Git Switch command is solely dedicated to managing branches.
To switch between branches, we will need the name of the branch. To see the existing branches in our repository, we can use the Git Branch command.
$ git branch
The above command will just output the names of the local branch. To check the remote branches use the -r flag. We can also use the -a flag to view all the branches locally as well as remotely.
We can simply pass the name of the branch to the Git Checkout command and it will take us to that branch.
$ git checkout <branch-name>
Use the -(hyphen) to switch to the previously checked-out branch. We don't need to enter the branch name when using this.
$ git checkout -
We can also create and switch to a new branch by using a single Git Checkout command. Use the -b flag to do this. By default, a new branch will be created on our current HEAD. We can also use a commit hash to create a new branch based on that commit or we can pass the name of an existing branch to create a new branch based on the existing branch.
To create a new branch based on the current HEAD, use the below command.
$ git checkout -b <new-branch-name>
To create a new branch based on a commit:
$ git checkout -b <new-branch-name> <commit-hash>
To create a new branch based on an existing branch:
$ git checkout -b <new-branch-name> <existing-branch>
We can also use the Git Switch command to move to a different branch.
$ git switch <branch-name>
As discussed above, we can use the -(hyphen) to quickly jump to our previous branch without entering its name.
$ git switch -
To create and switch to a new branch, use the -c flag with the Git Switch command. We can also pass the branch name or commit hash to base the new branch on an existing branch or commit. By default, it will create a new branch at the HEAD.
$ git switch -c <new-branch-name>
We will be frequently creating and switching between branches when working with Git. Switching branches is pretty simple and Git provides us with the Git Checkout command and the Git Switch command to change branches. To create and switch to a new branch, we can use the -b flag with Git Checkout or the -c flag with the Git Switch command.