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:

  1. 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 shows ref: refs/heads/master by convention. The error is thrown because HEAD is ambiguous. You have no history, thus any value passed to rev-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.

  2. 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, the HEAD pointer is pointing at a commit. You get HEAD as the return using method (1) because rev-parse is just echoing the passed refspec value in the error. Try it with blah; you'll see the same thing.

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