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 i
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.
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:
-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.-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.)