I want to check local branches of a repo, since there will always be a local master
or main
branch
Taking that as a reliable description of your intended use-case environment, since in general use it's often enough not true,
What Git command can I use to return the first branch of these which exists?
A concise way of doing it is
if git cat-file -e refs/heads/master 2>&-; then echo master
elif git cat-file -e refs/heads/main 2>&-; then echo main
fi
but for anything even a little more elaborate you're likely to want for-each-ref,
{ git for-each-ref --format='%(refname)' refs/{heads,remotes/*}/master;
git for-each-ref --format='%(refname)' refs/{heads,remotes/*}/main;
} | sed -E 's,(.*)/,\1 ,' | sort -usk1,1
which gives the answer for local branches and all tracked remotes without any foofaraw.
In my git
repo this reports refs/remotes/origin master
, for instance, and the Git project keeps both branch names in lockstep. But as someone else pointed out, some projects keep master
around as a record of where it was when they switched away, and as you might have noticed I don't have a master
or main
branch. My make
branch tracks origin/next
, that's the one I run my deployments from, and there's a couple others for little projects.
To do just local branches do
{ git for-each-ref --format='%(refname:short)' refs/heads/master;
git for-each-ref --format='%(refname:short)' refs/heads/main;
} | head -1
See the for-each-ref
examples, it was built for this.