Is there any difference between git checkout and git checkout -b

前端 未结 2 387
萌比男神i
萌比男神i 2021-01-28 03:16

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

相关标签:
2条回答
  • 2021-01-28 03:16

    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.

    0 讨论(0)
  • 2021-01-28 03:34

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

    0 讨论(0)
提交回复
热议问题