如何使用新的 `git switch` 语法来创建新分支?

Tay*_*ine 6 git

我习惯于git checkout -b branchname切换到一个名为branchname. 我该怎么做git switch

Von*_*onC 7

实际上,--create在使用以下命令创建新分支时,您甚至(总是)不需要该选项git switch

如果该分支与远程跟踪分支匹配,它将创建一个本地分支,并自动跟踪远程分支!

意思是简单git switch <branch>就足够了。

如果<branch>未找到,但在一个<remote>具有匹配名称的远程(称为)中确实存在跟踪分支,则视为等效于:

$ git switch -c <branch> --track <remote>/<branch>
Run Code Online (Sandbox Code Playgroud)

如果分支存在于多个遥控器中并且其中一个由checkout.defaultRemote配置变量命名,我们将使用该分支来消除歧义,即使它<branch>在所有遥控器中都不是唯一的。如果不明确但存在于远程分支上,则将
其设置为例如checkout.defaultRemote=origin始终从那里签出远程分支。 另见<branch>origin
checkout.defaultRemotegit config

另外,如果你错误地切换到远程跟踪分支,它会失败(而不是git checkout,它会从所述远程分支创建一个分离的 HEAD!)

git switch origin/master
fatal: a branch is expected, got remote branch 'origin/master'
Run Code Online (Sandbox Code Playgroud)

对比

git checkout origin/master
Note: switching to 'origin/master'.

You are in 'detached HEAD' state
Run Code Online (Sandbox Code Playgroud)

  • 嗯,“git switch newbranch”对我来说会导致“致命:无效引用:newbranch”。 (2认同)
  • @TaylorKline 我想是因为 `newbranch` 名称与任何 `remotes/origin/&lt;branches&gt;` 名称都不匹配。如果是这种情况,您将需要“git switch -c newbranch”,正如您在答案中提到的那样。 (2认同)

Tay*_*ine 5

创建新分支的语法git switchgit switch -c branchnameor git switch --create branchname