Right and fast way to test git directory and git branch?
Doesn't fully answer your questions but probably a bit more than just a comment:
-
Based on other comments in your answer, I think the error you saw is
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
That occurs because you're conducting these tests on a brand new git repository, one that has no committed work. Not only is this not really a fair test (your performance will by definition be worse on a larger repository), it is in nearly every way an edge case. For example,.git/HEAD
showsref: refs/heads/master
by convention. The error is thrown becauseHEAD
is ambiguous. You have no history, thus any value passed torev-parse
would be treated the same. Additionally, this doesn't exit 0 for me:$ git init /tmp/test && cd /tmp/test $ git rev-parse --abbrev-ref HEAD $ echo $? 128
In sum, don't sweat this error. Grab yourself one of the huge android repos, or perhaps the linux kernel, and test your prompt there.
HEAD
is not a branch. It's a pointer to the checked-out state. When you've got a branch checked out, it's a symbolic reference to that branch. When you're in 'detached HEAD' state, theHEAD
pointer is pointing at a commit. You getHEAD
as the return using method (1) becauserev-parse
is just echoing the passed refspec value in the error. Try it withblah
; you'll see the same thing.-
I haven't actually benchmarked solutions, but a few things you might try (both are used in my zsh prompt, which I didn't write, and both have performed quite well):
git rev-parse --is-inside-work-tree ;# avoids your 'test -d .git' call ref=$(git symbolic-ref HEAD 2> /dev/null) ;# grab the full refspec branch=$(echo ${ref#refs/heads/}) ;# extract the branch name