How can I use the new `git switch` syntax to create a new branch?

*爱你&永不变心* 提交于 2021-02-19 04:22:49

问题


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 the origin 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!