I can find the current git branch name by doing either of these:
git branch | awk \'/^\\*/ { print $2 }\'
git describe --contains --all HEAD
<
A sed solution:
git log -1 --pretty=%D HEAD | sed 's/.*origin\///g;s/, .*//g'
This uses log to check the last item for its presence on a branch. Then sed finds the branch preceded by origin/ and removes the phrase and everything before it. Then sed does another removal of any possible additional listed branches (comma and everything after it). The reason last log was used as a sanity check to ensure this detached HEAD is not a commit above known branch HEADs.
If this is empty, failsafe logic can be implemented to label the branch "detached" (or "undefined"?) or to ensure it's up-to-date or rolled back to the tip of a known HEAD.