I wanted a single line that I could parse in a Windows CMD shell (most of the answers here use unix commands). Most of the answers also had problems with sparse checkouts and detached heads.
git branch
gives a list of branches that are available in the working copy, with an * in front of the checked out one. This is good for a quick look but not for parsing.
git rev-parse --abbrev-ref HEAD
just showed HEAD as the branch when using it on a detached HEAD checkout. Similarly when using
git symbolic-ref HEAD
I got fatal: ref HEAD is not a symbolic ref when using a detached head that was from a tag.
git describe --contains --all HEAD
seems to work most of the time and was close to what I want, but with some repos just returned a blank line.
git status
works except it lists all differences in the repo which makes it a bit difficult to parse.
I ended up settling on the following;
git status |findstr/n ^^|findstr "^[1]: ^[0]:"
This gives output like the following;
1:HEAD detached at 2.30.20
or
1:On branch master