Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name only option for `git branch --list`?

Tags:

git

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

like image 664
antak Avatar asked Mar 16 '16 03:03

antak


People also ask

What command is used to create List rename and delete branches?

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.

Can a branch name have '/' in git?

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


3 Answers

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

like image 147
torek Avatar answered Oct 21 '22 00:10

torek


git branch --format='%(refname:short)'
like image 26
Cyril Bouthors Avatar answered Oct 20 '22 22:10

Cyril Bouthors


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
like image 1
antak Avatar answered Oct 20 '22 22:10

antak