How to find the current git branch in detached HEAD state

A more porcelain way:

git log -n 1 --pretty=%d HEAD

# or equivalently:
git show -s --pretty=%d HEAD

The refs will be listed in the format (HEAD, master) - you'll have to parse it a little bit if you intend to use this in scripts rather than for human consumption.

You could also implement it yourself a little more cleanly:

git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$(git rev-parse HEAD)/ {print \$2}"

with the benefit of getting the candidate refs on separate lines, with no extra characters.


I needed a bit different solution for Jenkins because it does not have local copies of the branches. So the current commit must be matched against the remote branches:

git ls-remote --heads origin | grep $(git rev-parse HEAD) | cut -d / -f 3

or without network:

git branch --remote --verbose --no-abbrev --contains | sed -rne 's/^[^\/]*\/([^\ ]+).*$/\1/p'

It's also worth noting that this might return multiple branch names when you have multiple branch heads at the same commit.

UPDATE:

I just noticed that Jenkins sets GIT_BRANCH environment variable which contains a value like origin/master. This can be used to get git branch in Jenksin too:

echo $GIT_BRANCH | cut -d / -f 2