这里的大多数答案都过于复杂化输出的解析git branch -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 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
但我并不特别关心这种方法,因为它会在执行结帐时在分支之间切换。完成后,它会将您留在它创建的最后一个分支上。
参考