git branch
outputs a list of branches, but also outputs other human-oriented fluff such as an asterisk (*
) beside the current branch.
$ git branch
* (HEAD detached at origin/master)
branch_foo
some/branch_bar
How do I get a more machine parsable output (e.g. just the name of branches) for scripting use etc.?
The git branch command lets you create, list, rename, and delete branches. It doesn't let you switch between branches or put a forked history back together again. For this reason, git branch is tightly integrated with the git checkout and git merge commands.
Git imposes the following rules on how references are named: They can include slash / for hierarchical (directory) grouping, but no slash-separated component can begin with a dot . or end with the sequence . lock . They must contain at least one / .
The general scripting command for working with references is git for-each-ref
.
Branch references live in the refs/heads/
part of the name-space, so use git for-each-ref refs/heads
to obtain them all.
By default, git for-each-ref
prints three items: '%(objectname) %(objecttype) %(refname)'
, Use a different --format
to change this. In this case, you probably want:
git for-each-ref --format='%(refname:short)' refs/heads
but see the documentation for all the available formatting directives. (Note also that git for-each-ref
got a fair bit of attention in git 2.6 and 2.7: --contains
, --merged
, --no-merged
, and --points-at
are new. In older versions of git, the first three are only available via git branch
.)
git branch --format='%(refname:short)'
The output of git show-ref --heads
is machine parsable.
$ git show-ref --heads
a419c3625028324901ce09533de6377740c9b551 refs/heads/branch_foo
38760602162a7e7aa7c75f1797342f3b65262999 refs/heads/some/branch_bar
If you just want branch names, something like this will do that:
$ git show-ref --heads | cut -d/ -f3-
branch_foo
some/branch_bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With