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

$ git branch
* master

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

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

当前回答

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

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

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

该行应替换为:

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

然后运行git fetch等。。。

其他回答

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

对于使用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

玩git时要小心,循序渐进。

$ git remote update  //This will update your local
$ git branch -a      //This will list all the branches(After updating you can now 
see the new branch in the list)
$ git checkout your_branch_name

如果您这样做:

git fetch origin

然后他们都会在当地。如果随后执行以下操作:

git branch -a

您将看到它们列为remotes/origin/分支名称。因为他们在当地,你可以随心所欲地和他们在一起。例如:

git diff origin/branch-name 

or

git merge origin/branch-name

or

git checkout -b some-branch origin/branch-name

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

git checkout --track origin/%branchname%