可以使用远程URL而不是名称来检查分支吗?

Ale*_*nov 5 git

git checkout -b <name> <remote>/<branch>似乎需要一个命名的遥控器.有没有办法让它只在一个URL下工作?原因是团队中的人有不同的遥控器名称(例如gitlaboriginvs origingithub),我想忽略脚本中的这种差异.

一种可能性是在脚本开头给远程名称并最后删除它,但我宁愿避免使用它.

abl*_*igh 3

不,没有任何方法可以使第二个参数git checkout -b与 URL 一起使用,而不是分支名称(以<remote>/<branch>或其他形式)。

\n\n

从手册页:

\n\n
   git checkout -b|-B <new_branch> [<start point>]\n       Specifying -b causes a new branch to be created as if git-branch(1) were\n       called and then checked out. In this case you can use the --track or\n       --no-track options, which will be passed to git branch. As a convenience,\n       --track without -b implies branch creation; see the description of\n       --track below.\n\n       If -B is given, <new_branch> is created if it doesn\xe2\x80\x99t exist; otherwise,\n       it is reset. This is the transactional equivalent of\n\n           $ git branch -f <branch> [<start point>]\n           $ git checkout <branch>\n\n       that is to say, the branch is not reset/created unless "git checkout" is\n       successful.\n
Run Code Online (Sandbox Code Playgroud)\n\n

git branch引用的第二个参数start point必须是指向现有存储库中的提交的内容。由 URL 寻址的分支(甚至可能未获取)将无法实现此目的。此外,没有办法将分支编码为 git URL 作为标准(github 可能有一些东西,但我认为没有,否则 golang 导入会容易得多......)

\n\n

如果您想让这项工作成功,您将需要:

\n\n
    \n
  • 解析 的输出git remote -v show以获取适当的远程名称
  • \n
  • 执行 agit fetch以确保相关分支被拉下(git fetch --all可能是你的朋友)
  • \n
  • 将分支名称附加到远程名称,等等git checkout -b
  • \n
\n\n

这是一个经过简单测试的 bash 脚本:

\n\n
#!/bin/bash\n#\n# usage: scriptname repo branchname\n#\n# where repo is the URL, branchname is the branchname to create\nrepo="$1"\nbranchname="$2"\nremote=$(git remote -v show | perl -n -e \'if (m,^(\\w+)\\s+(\\S+)\\b, && $2 eq \'"\'${repo}\'"\') {print "$1\\n" ; exit 0}\')\nif [ "$remote" == "" ] ; then\n    echo cannot find "${repo}" 1>&2\n    exit 1\nfi\ngit fetch --all && git checkout -b "${branchname}" "remotes/${remote}/${branchname}"\n
Run Code Online (Sandbox Code Playgroud)\n