问题
I am used to git checkout -b branchname
to switch to a new branch named branchname
. How do I do the same with git switch
?
回答1:
The syntax for creating a new branch with git switch
is git switch -c branchname
or git switch --create branchname
.
回答2:
Actually, you don't even (always) need the --create
option when creating a new branch with git switch:
if that branch matches a remote tracking one, it will create a local branch, and automatically track the remote one!
Meaning a simple git switch <branch>
is enough.
If
<branch>
is not found but there does exist a tracking branch in exactly one remote (call it<remote>
) with a matching name, treat as equivalent to:
$ git switch -c <branch> --track <remote>/<branch>
If the branch exists in multiple remotes and one of them is named by the
checkout.defaultRemote
configuration variable, we’ll use that one for the purposes of disambiguation, even if the<branch>
isn’t unique across all remotes.
Set it to e.g.checkout.defaultRemote=origin
to always checkout remote branches from there if<branch>
is ambiguous but exists on theorigin
remote.
See also checkout.defaultRemote in git config.
Plus, if you switch by mistake to a remote tracking branch, it fails (as opposed to git checkout
, which would create a detached HEAD from said remote branch!)
git switch origin/master
fatal: a branch is expected, got remote branch 'origin/master'
Vs.
git checkout origin/master
Note: switching to 'origin/master'.
You are in 'detached HEAD' state
来源:https://stackoverflow.com/questions/58124219/how-can-i-use-the-new-git-switch-syntax-to-create-a-new-branch