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
?

- 908
- 3
- 9
- 30
2 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 theorigin
remote.
See alsocheckout.defaultRemote
ingit 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

- 1,262,500
- 529
- 4,410
- 5,250
-
2Hmm, `git switch newbranch` results in `fatal: invalid reference: newbranch` for me. – Taylor Kline Sep 30 '19 at 14:20
-
2@TaylorKline I suppose because `newbranch` name does not match any of the `remotes/origin/
` names. If that is the case, you would need `git switch -c newbranch`, as you mention in your answer. – VonC Sep 30 '19 at 14:53
The syntax for creating a new branch with git switch
is git switch -c branchname
or git switch --create branchname
.

- 908
- 3
- 9
- 30