Git switch branches

When you work on different git branches, you may need to switch between branches in your command line (terminal). In Git’s terminology, switching branches refers to the “git checkout” command.

Anyways, to switch or change a git branch type the following command and hit enter: git checkout branch_name_here

Replace the branch_name_here with the actual branch name you want to switch to.

The above command will allow you to jump/navigate from one branch to another.

How to switch from the master branch to another branch?

Let’s say you want to switch from the master branch to another branch named “about-page.” To switch to this “about-page” branch, use the following command:

git checkout about-page

git checkout to another branch from master, git switch branch

If you’re new to Git, you have to know that you need to create a branch before you switch to it. That means you can’t switch to a branch that does not exist.

Create a new branch before you switch to it

To create a new branch, use the following command: git branch new_branch_name

Command for creating a new git branch in the terminal

In the above command, it created a new branch named “header-edit.”

But if you already have created different branches and want to switch to any one of them, that’s fine.

How to list down all available branches

To see the all available branches you have, use the following command: git branch

list of git branches

The star “*” previous to the branch name means you’re currently on this branch. The above screenshot shows the list of available branches and it also shows that the terminal/command line is currently pointing to the “sidebar” branch.

How can you switch to the master branch from another feature branch in Git?

To switch from a feature branch to the master branch, use the following command:

git checkout master

Switch from a feature branch to the master branch in Git

In the above screenshot, you see that I switched from the “about-page” to the “master” branch.

Create a new branch and switch to the branch in one command

Until this point, you learned how to create a new branch, list down all branches, and switch to a branch from another. But if you want to create a branch and at the same time you want to switch to the branch, there is also a command for it (as you see below).

git checkout -b name_of_the_new_branch

Single command for creating a new Git branch and point to it

The command in the above screenshot creates a new branch called “sidebar” and switches to the newly created branch (sidebar).

Git branch-related commands in action

Learn more about Git

Conclusion

In this post, I showed you how to switch between branches in Git. Also, you learned how to create & switch to a new branch in one single command. I tried to cover everything you need to know about switching branches and provided you with all the commands and screenshots. Therefore if you still have questions, please let me know.