我的主分支和开发分支在GitHub上被远程跟踪。如何克隆这两个分支?
当前回答
#!/bin/bash
for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
git branch --track ${branch#remotes/origin/} $branch
done
这些代码将把所有远程分支代码拉到本地存储库。
其他回答
在这里,我为您编写了一个很好的函数,使其易于重复
gitCloneAllBranches() { # clone all git branches at once easily and cd in
# clone as "bare repo"
git clone --mirror $1
# rename without .git extension
with_extension=$(basename $1)
without_extension=$(echo $with_extension | sed 's/.git//')
mv $with_extension $without_extension
cd $without_extension
# change from "bare repository" to not
git config --bool core.bare false
# check if still bare repository if so
if [[ $(git rev-parse --is-bare-repository) == false ]]; then
echo "ready to go"
else
echo "WARNING: STILL BARE GIT REPOSITORY"
fi
# EXAMPLES:
# gitCloneAllBranches https://github.com/something/something.git
}
只需执行以下操作:
$ git clone git://example.com/myproject
$ cd myproject
$ git checkout branchxyz
Branch branchxyz set up to track remote branch branchxyz from origin.
Switched to a new branch 'branchxyz'
$ git pull
Already up-to-date.
$ git branch
* branchxyz
master
$ git branch -a
* branchxyz
master
remotes/origin/HEAD -> origin/master
remotes/origin/branchxyz
remotes/origin/branch123
你看,gitclonegit://example.com/myprojectt获取所有内容,甚至是分支,您只需签出它们,就可以创建本地分支。
下面是根据前面的答案改编的跨平台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,它总是让您在尝试时感到困扰。
下面是另一个简短的单行命令为所有远程分支创建本地分支:
(git branch -r | sed -n '/->/!s#^ origin/##p' && echo master) | xargs -L1 git checkout
如果已经创建了跟踪本地分支,它也可以正常工作。您可以在第一个git克隆之后或以后的任何时间调用它。
如果克隆后不需要签出主分支,请使用
git branch -r | sed -n '/->/!s#^ origin/##p'| xargs -L1 git checkout
截至2017年初,该评论中的答案有效:
gitfetch<origin name><branch name>为您关闭分支。虽然这不会同时拉动所有分支,但您可以对每个分支单独执行此操作。