我克隆了一个包含许多分支的Git存储库。然而,git分支仅显示一个:

$ git branch
* master

我如何在本地拉所有分支,所以当我执行git分支时,它会显示以下内容?

$ git branch
* master
* staging
* etc...

当前回答

下面是接受答案中提供的一行程序的Perl版本:

git branch-r | perl-e'while(<>){chop;my$remote=$_;my($local)=($remote=~/origin\/(.*)/);打印“git branch--track$local$remote\n”;}'>一些输出文件

如果愿意,可以将输出文件作为Shell脚本运行。

我们无意中删除了Stash项目存储库。幸运的是,就在意外损失之前,有人制造了一个叉子。我将叉子克隆到了我的本地(将省略我是如何做到这一点的细节)。当我把叉子完全放在本地时,我跑了一条单行道。我修改了远程服务器的URL(在我的例子中是源URL),以指向我们要恢复到的目标存储库:

gitremoteseturl-origin<remoteurl>

最后将所有分支都推到原点,如下所示:

git push—所有原点

我们又回到了生意上。

其他回答

要列出远程分支,请执行以下操作:

git branch -r

要将远程分支签出为本地分支,请执行以下操作:

git checkout -b local_branch_name origin/remote_branch_name

TL;DR答案

git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

(似乎pull会从所有遥控器获取所有分支,但我总是先获取,以确保安全。)

仅当服务器上存在本地分支未跟踪的远程分支时,才运行第一个命令。

完整答案

您可以像这样从所有遥控器获取所有分支:

git fetch --all

这基本上是一个有力的动作。

fetch更新远程分支的本地副本,因此这对本地分支总是安全的,但是:

fetch不会更新本地分支(跟踪远程分支);如果要更新本地分支,仍然需要拉动每个分支。fetch不会创建本地分支(跟踪远程分支),您必须手动执行此操作。如果要列出所有远程分支:查看所有的分支

要更新跟踪远程分支的本地分支,请执行以下操作:

git pull --all

然而,这仍然不够。它只适用于跟踪远程分支的本地分支。要跟踪所有远程分支,请在git pull-all之前执行以下oneliner:

git branch -r | grep -v '\->' | sed "s,\x1B\[[0-9;]*[a-zA-Z],,g" | while read remote; do git branch --track "${remote#origin/}" "$remote"; done

P.S.AFAIK git fetch--all和git远程更新是等效的。



Kamil Szot的评论,人们发现这很有用。

我必须使用:对于“gitbranch-r”中的remote;do git branch--跟踪${remote#origin/}$remote;完成因为您的代码创建了名为origin/branchname和每当我参考它。

确保所有远程分支都可以在.git/config文件中获取。

在本例中,只有原始/生产分支是可获取的,即使您尝试执行git fetch,除了获取生产分支之外,一切都不会发生:

[origin]
fetch = +refs/heads/production:refs/remotes/origin/production

该行应替换为:

[origin]
fetch = +refs/heads/*:refs/remotes/origin/*

然后运行git fetch等。。。

我写了一个小脚本来管理克隆一个新的repo,并为所有远程分支创建本地分支。

您可以在此处找到最新版本:

#!/bin/bash

# Clones as usual but creates local tracking branches for all remote branches.
# To use, copy this file into the same directory your git binaries are (git, git-flow, git-subtree, etc)

clone_output=$((git clone "$@" ) 2>&1)
retval=$?
echo $clone_output
if [[ $retval != 0 ]] ; then
    exit 1
fi
pushd $(echo $clone_output | head -1 | sed 's/Cloning into .\(.*\).\.\.\./\1/') > /dev/null 2>&1
this_branch=$(git branch | sed 's/^..//')
for i in $(git branch -r | grep -v HEAD); do
  branch=$(echo $i | perl -pe 's/^.*?\///')
  # this doesn't have to be done for each branch, but that's how I did it.
  remote=$(echo $i | sed 's/\/.*//')
  if [[ "$this_branch" != "$branch" ]]; then
      git branch -t $branch $remote/$branch
  fi
done
popd > /dev/null 2>&1

要使用它,只需将其复制到git bin目录中(对我来说,这是C:\Program Files(x86)\git\bin\git cloneall),然后在命令行上:

git cloneall [standard-clone-options] <url>

它照常克隆,但为所有远程分支创建本地跟踪分支。

git remote add origin https://yourBitbucketLink

git fetch origin

git checkout -b yourNewLocalBranchName origin/requiredRemoteBranch (use tab :D)

现在本地您的NewLocalBranchName是您所需的RemoteBranch。