16

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.?

antak
  • 19,481
  • 9
  • 72
  • 80
  • 2
    As a general rule for scripts, read the `git(1)` man page and use the "plumbing" commands rather than the "porcelain" commands that are usually used. – o11c Mar 16 '16 at 03:35

4 Answers4

20

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.)

Noelle L.
  • 100
  • 6
torek
  • 448,244
  • 59
  • 642
  • 775
  • `git for-each-ref --format="%(refname)" refs/heads/` works for me. Note: This adds a superfluous `refs/heads/` in front of the branch name, which may or may not be a good thing depending on the use case. – antak Mar 16 '16 at 05:30
  • Accepting on the virtue that I prefer a solution without piping where possible. – antak Mar 16 '16 at 05:33
16
git branch --format='%(refname:short)'
Cyril Bouthors
  • 1,224
  • 10
  • 7
2

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
antak
  • 19,481
  • 9
  • 72
  • 80
-1

The following command will be a help.

git branch -a | sed -e 's/\(^\* \|^ \)//g' | cut -d " " -f 1

gzh
  • 3,507
  • 2
  • 19
  • 23