git branch
命令会输出所有分支列表,同时也会输出其他人性化的信息,比如当前分支旁边带有一个星号(*
)。
$ git branch
* (HEAD detached at origin/master)
branch_foo
some/branch_bar
如何获取更适合机器解析的输出(例如,仅分支名称)以供脚本使用?
git branch
命令会输出所有分支列表,同时也会输出其他人性化的信息,比如当前分支旁边带有一个星号(*
)。
$ git branch
* (HEAD detached at origin/master)
branch_foo
some/branch_bar
如何获取更适合机器解析的输出(例如,仅分支名称)以供脚本使用?
处理引用的通用脚本命令是 git for-each-ref
。
分支引用存储在名称空间中的 refs/heads/
部分,因此使用 git for-each-ref refs/heads
来获取所有分支引用。
git for-each-ref
默认打印三个项:'%(objectname) %(objecttype) %(refname)'
,使用不同的 --format
来更改。在这种情况下,您可能需要:
git for-each-ref --format='%(refname:short)' refs/heads
但请参阅文档以查看所有可用的格式指令。(还要注意,在Git 2.6和2.7中,git for-each-ref
引起了相当大的关注:--contains
,--merged
,--no-merged
和--points-at
是新的。在旧版本的 Git 中,前三个只能通过 git branch
访问。)
git for-each-ref --format="%(refname)" refs/heads/
对我来说很有效。请注意:这会在分支名称前面添加一个多余的 refs/heads/
,根据用例可能是好事或坏事。 - antakgit branch --format='%(refname:short)'
git show-ref --heads
的输出是可被机器解析的。 < /p >
$ git show-ref --heads
a419c3625028324901ce09533de6377740c9b551 refs/heads/branch_foo
38760602162a7e7aa7c75f1797342f3b65262999 refs/heads/some/branch_bar
$ git show-ref --heads | cut -d/ -f3-
branch_foo
some/branch_bar
git branch -a | sed -e 's/\(^\* \|^ \)//g' | cut -d " " -f 1
git(1)
手册并使用“管道”命令而不是通常使用的“瓷器”命令。 - o11c