David Portabella
David Portabella

Reputation: 12720

git show remote branches, and filter out HEAD and any other symbolic references

I am writing a script that takes a git repo, and it runs a test for each remote branch. I use the following to get the names of the remote branches:

$ git branch -l -r
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
  remotes/origin/br1

however, I also get symbolic references, such as HEAD. How to I filter out HEAD and any other symbolic reference?

Upvotes: 1

Views: 344

Answers (1)

torek
torek

Reputation: 489035

Any time you want to operate on a set of references, the correct plumbing (script-able) command is likely to be git for-each-ref.

In this case, for instance:

$ git for-each-ref --format '%(refname)' refs/remotes |
> while read ref; do
>     if git symbolic-ref -q $ref > /dev/null; then
>         echo sym $ref
>     else
>        echo reg $ref
>    fi
> done
sym refs/remotes/origin/HEAD
reg refs/remotes/origin/maint
reg refs/remotes/origin/master
reg refs/remotes/origin/next
reg refs/remotes/origin/pu
reg refs/remotes/origin/todo

To skip the symbolic references entirely, you can change the if/then clause to if ! git symbolic-ref -q $ref > /dev/null; then (and drop the else entirely). To do something interesting with the symbolic references and their targets, save the output from git symbolic-ref in a variable, instead of redirecting it to /dev/null (but retain the -q to prevent it from complaining to stderr for all non-symbolic refs).

The for-each-ref command lets you operate on any sensible subset of references, including specific remotes, or all local branches (refs/heads).

Upvotes: 2

Related Questions