此处的大多数答案都过于复杂了的输出解析git branch -r
。您可以使用以下for
循环针对远程服务器上的所有分支创建跟踪分支,如下所示。
例
假设我有这些远程分支机构。
$ git branch -r
origin/HEAD -> origin/master
origin/development
origin/integration
origin/master
origin/production
origin/staging
确认除了本地主机以外,我们还没有跟踪其他任何内容:
$ git branch -l # or using just git branch
* master
您可以使用这一衬板来创建跟踪分支:
$ for i in $(git branch -r | grep -vE "HEAD|master"); do
git branch --track ${i#*/} $i; done
Branch development set up to track remote branch development from origin.
Branch integration set up to track remote branch integration from origin.
Branch production set up to track remote branch production from origin.
Branch staging set up to track remote branch staging from origin.
现在确认:
$ git branch
development
integration
* master
production
staging
删除它们:
$ git br -D production development integration staging
Deleted branch production (was xxxxx).
Deleted branch development (was xxxxx).
Deleted branch integration (was xxxxx).
Deleted branch staging (was xxxxx).
如果使用-vv
开关,则git branch
可以确认:
$ git br -vv
development xxxxx [origin/development] commit log msg ....
integration xxxxx [origin/integration] commit log msg ....
* master xxxxx [origin/master] commit log msg ....
production xxxxx [origin/production] commit log msg ....
staging xxxxx [origin/staging] commit log msg ....
for循环的细分
循环基本上会调用该命令git branch -r
,并使用过滤掉输出中的任何HEAD或master分支grep -vE "HEAD|master"
。为了获得分支的名称减去origin/
子字符串,我们使用Bash的字符串操作${var#stringtoremove}
。这将从变量中删除字符串“ stringtoremove” $var
。在我们的例子中,我们origin/
要从变量中删除字符串$i
。
注意:或者,您也可以使用它git checkout --track ...
来执行此操作:
$ for i in $(git branch -r | grep -vE "HEAD|master" | sed 's/^[ ]\+//'); do
git checkout --track $i; done
但是我并不特别在意这种方法,因为它在执行签出时会在分支之间切换。完成后,它将留在创建的最后一个分支上。
参考资料
git checkout --track origin/branchname