86

Creating and using a new branch involves two commands:

$ git branch new_branch_name
$ git checkout new_branch_name

I tend to forget the latter, which can be annoying. Is there a way to do this using a single command? Perhaps using an alias, or something similar? I know I could write a shell function, but that seems a bit much work for such a simple and common task.

Bazaar does support this to some degree using the bzr branch --switch notation.

MvG
  • 57,380
  • 22
  • 148
  • 276
  • 1
    Was about to downvote for lack of research effort, but then I realized you were answering your own question. –  Jul 30 '13 at 23:56

3 Answers3

125

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 if git-branch(1) were called and then checked out.

Just what I was looking for.

Neuron
  • 5,141
  • 5
  • 38
  • 59
MvG
  • 57,380
  • 22
  • 148
  • 276
  • 2
    [“And how should I create a branch?” “Use `git checkout`.”](http://stevelosh.com/blog/2013/04/git-koans/#one-thing-well) – 13ren Jul 30 '13 at 22:52
  • 13ren: Updated link: https://stevelosh.com/blog/2013/04/git-koans/#s2-one-thing-well – piegames Jan 12 '21 at 12:54
28

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
P-Gn
  • 23,115
  • 9
  • 87
  • 104
10

There are two oneliners for this in git.

  1. git checkout -b new_branch_name
  2. git switch -c new_branch_name

Under the hood, both do the same thing:

git branch new_branch_name
git checkout new_branch_name
Neuron
  • 5,141
  • 5
  • 38
  • 59
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79