0

I'm very new to git so I'm about to make my fist commit, so for this I have created a branch by typing git checkout my_branch .This worked fine. But after I saw in the documentation that It is used git checkout -b my_branch

Is there any difference between those?

2
  • git -b checkout is short for git branch and then git checkoutbut how about excluding the -bin git checkout Does it have any effect? Commented May 3, 2019 at 17:44
  • What you might infer from the below answers, but they don't spell out explicitly, is that if, as you say, git checkout my_branch (with no -b) worked, then the branch already existed and what happened may not be what you think happened. (Due to git being hlepful - in a way that really is useful but isn't easy to explain - the branch might not have existed locally yet, which is what torek's answer draws out in a bit more detail.) Commented May 3, 2019 at 18:14

2 Answers 2

6

Yes:

$ git checkout asdfadsf
error: pathspec 'asdfasdf' did not match any file(s) known to git

This failed because I don't have a branch asdfasdf. Git tried to treat asdfasdf as a file name, and I don't have a file named asdfasdf either.

$ git checkout -b asdfasdf
Switched to a new branch 'asdfasdf'

This succeeded and created a new branch.

On the other hand, I don't have a branch named maint, and yet:

$ git checkout maint
Branch 'maint' set up to track remote branch 'maint' from 'origin'.
Switched to a new branch 'maint'

This, too, created a new branch, maint. But notice how it looks different. It still says Switched to a new branch, but first it says Branch 'maint' set up to track remote branch 'maint' from 'origin'.

The reasoning behind this is a little complicated, but it boils down to this:

  • Without -b, if you ask for a branch that you don't have, Git will try some alternatives. Some of them may work! When it works the way maint did here, the new branch has an upstream set already.
  • With -b, Git will just create the branch, no questions asked (provided that creating a new branch is possible). The new branch won't be set up with an upstream. If you already have the branch, you get an error.

If you want a branch with an upstream set—for instance, if there's an origin/feature/x123 and you want your own feature/x123 created to match—you don't want the -b option, because that won't do the search for an upstream origin/feature/x123. If you don't want an upstream set, you do want the -b option.

(Whether and when you want the upstream set for you is a separate question. Search StackOverflow for the existing answers.)

Sign up to request clarification or add additional context in comments.

Comments

0

when you run with -b you are telling git to create the branch for you. git checkout without -b requires the branch to exist already to work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.