Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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?

like image 614
Taylor Kline Avatar asked Sep 26 '19 20:09

Taylor Kline


1 Answers

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
like image 67
VonC Avatar answered Oct 02 '22 00:10

VonC