git 没有远程名称无法第一次检查分支

git can't checkout branch for the first time without the remote name

我已经克隆了一个 repo 并将我的分支添加为另一个远程但是我无法在没有指定哪个远程的情况下第一次签出分支(在本例中 master,这不是他们的默认分支)。

git clone https://github.com/facebook/zstd.git
cd zstd
git remote add jay https://github.com/jay/zstd.git
git fetch jay
git checkout master

error: pathspec 'master' did not match any file(s) known to git.

如果我指定遥控器,它会起作用:

git checkout -b master origin/master

Branch master set up to track remote branch master from origin.
Switched to a new branch 'master'

我很好奇为什么在这种情况下需要指定遥控器。我一定是记错了,但我很确定这并不总是必要的。对于两个存储库中的任何分支都是如此,例如,除非我明确指定 origin remote,否则 git checkout zstd_help 也会在第一次失败。

Git 版本:git version 2.7.4

此处的关键是您添加的第二个遥控器。如果您只是克隆 repo 并立即尝试签出 master,它将起作用:

mureinik@computer ~/src/git
$ git clone https://github.com/facebook/zstd.git
Cloning into 'zstd'...
remote: Enumerating objects: 9, done.
remote: Counting objects: 100% (9/9), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 43954 (delta 1), reused 0 (delta 0), pack-reused 43945
Receiving objects: 100% (43954/43954), 23.29 MiB | 682.00 KiB/s, done.
Resolving deltas: 100% (32256/32256), done.

mureinik@computer ~/src/git
$ cd zstd

mureinik@computer ~/src/git/zstd (dev)
$ git checkout master
Switched to a new branch 'master'
Branch 'master' set up to track remote branch 'master' from 'origin'.

一旦你添加 jay,远程分支名称 master 变得不明确(它可能指的是 origin/masterjay/master),因此当你尝试检查结果失败了。

我不确定这到底是什么时候发生的,但是较新版本的 git(我使用的是 2.28)在这种情况下会给出更清晰的错误消息:

# After adding the second "jay" remote

mureinik@computer ~/src/git/zstd (master)
$ git checkout verbose
hint: If you meant to check out a remote tracking branch on, e.g. 'origin',
hint: you can do so by fully qualifying the name with the --track option:
hint:
hint:     git checkout --track origin/<name>
hint:
hint: If you'd like to always have checkouts of an ambiguous <name> prefer
hint: one remote, e.g. the 'origin' remote, consider setting
hint: checkout.defaultRemote=origin in your config.
fatal: 'verbose' matched multiple (2) remote tracking branches