branch and checkout using a single command
Solution 1:
While writing the question, and finding “What is the difference between "git branch" and "git checkout -b"?” in the list of similar questions, I found the answer myself:
$ git checkout -b new_branch_name
I guess I was reading the man page for the wrong command, I was expecting this as part of the branch
command, not for checkout
. Quoting the man page for checkout
:
Specifying
-b
causes a new branch to be created as ifgit-branch(1)
were called and then checked out.
Just what I was looking for.
Solution 2:
Git introduced switch
in version 2.23 to handle changing of branches specifically and avoid the use of checkout
which can be confusing by the sheer amount of operations it can do.
Among other possibilites,
git switch <branch> # to switch to an existing branch
git switch -c <new_branch> # to create a new branch and switch to it
Solution 3:
There are two Oneliners at Git.
-
git checkout -b new_branch_name
. git switch -c new_branch_name
Under the hood, both do the same thing:
git branch new_branch_name
git checkout new_branch_name