这里的大多数答案都使git分支-r的输出解析过于复杂。您可以使用下面的for循环针对远程上的所有分支创建跟踪分支,如下所示。
例子
假设我有这些远程分支。
$ git branch -r
origin/HEAD -> origin/master
origin/development
origin/integration
origin/master
origin/production
origin/staging
确认我们在本地没有跟踪master以外的任何东西:
$ 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分支,你可以确认:
$ 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分支-r,使用grep -vE "HEAD|master"过滤输出中的任何HEAD或master分支。为了只得到分支的名称减去源/子字符串,我们使用Bash的字符串操作${var#stringtoremove}。这将从变量$var中删除字符串"stringtoremove"。在本例中,我们从变量$i中删除字符串origin/。
注意:或者你可以使用git checkout -track…要做到这一点:
$ for i in $(git branch -r | grep -vE "HEAD|master" | sed 's/^[ ]\+//'); do
git checkout --track $i; done
但我并不特别关心这个方法,因为它在执行签出时在分支之间切换。完成后,它将把您留在它创建的最后一个分支上。
参考文献
10.1. 操纵字符串-高级Bash脚本编写指南
3.5 Git分支-远程分支