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

$ git branch
* master

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

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

当前回答

对于使用PowerShell的Windows用户:

git branch -r | ForEach-Object {
    # Skip default branch, this script assumes
    # you already checked-out that branch when cloned the repo
    if (-not ($_ -match " -> ")) {
        $localBranch = ($_ -replace "^.*?/", "")
        $remoteBranch = $_.Trim()
        git branch --track "$localBranch" "$remoteBranch"
    }
}; git fetch --all; git pull --all

其他回答

为避免出现错误消息“fatal:名为“origin/master”的分支已存在。”,你可以试试我的解决方案:

git branch -r | grep -v '\->'  | grep -v `git branch | awk '/\*/ { print $2; }'`| while read remote; do git branch --track "${remote#origin/}" "$remote"; done

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和每当我参考它。

我写了一个小脚本来管理克隆一个新的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>

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

对于Visual Studio用户,在包管理器控制台上:

git branch | %{ git fetch upstream; git merge upstream/master}

如果您在fetch-all方面遇到问题,请跟踪远程分支:

git checkout --track origin/%branchname%