Home » Git » How to switch branch in git

How to switch branch in git

If you’re fairly new to git and you’ve found this post, you probably know how to clone a git repo, and now you’re wondering how to switch branches. When you clone the repo you’ll generally start out on the main/master branch, and now you want to change to a feature branch before you start coding. There are two different commands you can use to switch branch, they do exactly the same thing, so I’ll cover both.

Using git checkout

This is the original command to switch, or change branches in git, and the one most people are familiar with. You use the checkout command like this:

git checkout myFeatureBranch

After running that command, if you were to do a git status, you’ll see your current branch is now myFeatureBranch.

Using git switch

This is the newer of the two commands, and the one I use because it makes much more sense when you’re typing it and just feels more intuitive.

git switch myFeatureBranch

In the official documentation for git switch you can see that this command was added in git 2.23, when the developers of git decided to split some of the functionality that git checkout previously offered into two clearer uses. More on this below.

Is git checkout the same as git switch?

Git checkout does more than git switch, so no, but also yes :). If you compare the following two commands, then yes they do do exactly the same thing:

git checkout branchName
git switch branchName

But git checkout does more, whereas git switch is only used to switch branches.

What does git checkout do?

The command git checkout has two uses, one to change which branch you’re on where it’s used like this (already covered in this post):

git checkout branchName

… and it’s other use is to ‘checkout’ a file, hence it’s name I guess. But what does ‘checkout a file’ actually mean.

It means to discard your local changes to a file. So if you’ve been working on a file called newPage.jsx and you decide you’ve made a mess of it and want to start again, then by doing:

git checkout newPage.jsx

… your local branch will revert to the last committed version of the newPage.jsx file.

How to switch to master branch

So if you wanted to switch to master branch in git you would type:

git switch master

It’s that simple.