我的主分支和开发分支在GitHub上被远程跟踪。如何克隆这两个分支?


当前回答

这个Bash脚本帮助了我:

#!/bin/bash
for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
    git branch --track "${branch##*/}" "$branch"
done

它将为所有远程分支创建跟踪分支,除了master(您可能从原始clone命令中得到)。我想你可能还需要

git fetch --all
git pull --all

当然

一行:gitbranch-a|grep-vHEAD|perl-ne'chomp($_);s |^\*?\s*||;如果(m|(.+)/(.+)|&&not$d{$2}){print qq(git branch--track$2$1/$2\n)}否则{$d{$_}=1}‘|csh-xfs像往常一样:在复制rm-rf宇宙之前,在您的设置中进行测试一行的积分归用户cfi

其他回答

您可以轻松切换到分支,而无需使用花哨的“gitcheckout-b somebranch origin/somebranch”语法。您可以执行以下操作:

git checkout somebranch

Git将自动执行正确的操作:

$ git checkout somebranch
Branch somebranch set up to track remote branch somebranch from origin.
Switched to a new branch 'somebranch'

Git将检查在一个远程中是否存在同名的分支,如果存在,它将以与您明确指定的远程分支相同的方式对其进行跟踪。从git 1.8.2.1的git checkout手册页面:

如果未找到<branch>,但中确实存在跟踪分支只有一个具有匹配名称的远程(称为<remote>),视为相当于$git checkout-b<branch>--track<remote>/<branch>

当您执行“gitclone”时git://location“,将获取所有分支和标记。

为了在特定远程分支上工作,假设它是源远程分支:

git checkout -b branch origin/branchname

这是一个使用awk的答案。如果在新的回购协议中使用,这种方法就足够了。

git branch -r | awk -F/ '{ system("git checkout " $NF) }'

现有的分支将被简单地签出,或者声明为已经在其中,但是可以添加过滤器以避免冲突。

还可以修改它,以便调用显式git checkout-b<branch>-t<remote>/<branch>命令。

这个答案符合尼科斯·C的想法。


或者,我们可以指定远程分支。这是基于murphytalk的答案。

git branch -r | awk '{ system("git checkout -t " $NF) }'

它会对冲突发出致命的错误消息,但我认为它们是无害的。


这两个命令都可以别名。

使用nobody的答案作为参考,我们可以使用以下命令来创建别名:

git config --global alias.clone-branches '! git branch -r | awk -F/ "{ system(\"git checkout \" \$NF) }"'
git config --global alias.clone-branches '! git branch -r | awk "{ system(\"git checkout -t \" \$NF) }"'

就我个人而言,我会使用跟踪所有分支或跟踪所有分支。

看着问题的答案之一,我注意到可以缩短它:

for branch in  `git branch -r | grep -v 'HEAD\|master'`; do
    git branch --track ${branch##*/} $branch;
done

但是要注意,如果其中一个远程分支被命名,例如admin_master,它将不会被下载!

下面是根据前面的答案改编的跨平台PowerShell 7函数。

function Invoke-GitCloneAll($url) {
    $repo = $url.Split('/')[-1].Replace('.git', '')
    $repo_d = Join-Path $pwd $repo
    if (Test-Path $repo_d) {
        Write-Error "fatal: destination path '$repo_d' already exists and is not an empty directory." -ErrorAction Continue
    } else {
        Write-Host "`nCloning all branches of $repo..."
        git -c fetch.prune=false clone $url -q --progress &&
        git -c fetch.prune=false --git-dir="$(Join-Path $repo_d '.git')" --work-tree="$repo_d" pull --all
        Write-Host "" #newline
    }
}

注意:-c fetch.sprune=false使其包含通常会被排除的过时分支。如果你对它不感兴趣,就去掉它。


通过从函数中删除&&,可以在PowerShell 5.1(Windows 10中的默认值)中实现这一点,但这使得它即使在上一个命令失败时也会尝试git pull。因此,我强烈建议您只使用跨平台PowerShell,它总是让您在尝试时感到困扰。