DEV Community

Jessica Temporal
Jessica Temporal

Posted on • Originally published at jtemporal.com on

Creating a new branch and switching to it with just one command

Every time you create a new branch in Git you need to switch to that branch before committing. In this pro tip I’ll show you my favorite shortcut to create a branch and switch to it, all at the same time.

Traditional ways to create a branch

In Git, it is possible to create a branch and switch to it using the following command sequence:

git branch branch-1
git checkout branch-1

Enter fullscreen mode Exit fullscreen mode

As you can see in the image below:

image showing the result of the commands git branch and git checkout

Or even with the following sequence:

git branch branch-2
git switch branch-2

Enter fullscreen mode Exit fullscreen mode

Also visible in the image bellow:

image showing the result of the commands git branch and git switch

Shortcuts to create branches and switch branches at the same time

There’s nothing wrong with these two sequences of commands shown earlier, but there are two shortcuts to get the same result using just one command. The first using git checkout followed by the -b flag:

git checkout -b branch-3

Enter fullscreen mode Exit fullscreen mode

You can see the similar result to the one shown in the first example of this blog post:

image showing the result of the command git checkout -b branch-3

And if you prefer using the command git switch we have the following shortcut using the -c flag:

git switch -c branch-4

Enter fullscreen mode Exit fullscreen mode

Also with a similar result to what we saw previously:

image showing the result of the command git switch -c branch-4

GitFichas

Below you’ll find two GitFichas to help you remember these shortcuts:


GitFicha #014: git checkout -b name


GitFicha #035: git switch -c name

Now you know two shortcuts to create a branch and change to it with only one command.

Top comments (0)