Show the current branch name
Print the current branch name with git branch --show-current, which prints nothing on a detached HEAD, where rev-parse --abbrev-ref prints the word HEAD.
A script needs the name of the checked out branch, and the two common commands answer differently when there is none.
git init -q -b main demo && cd demo
git config user.email [email protected]; git config user.name Demo
git commit -q --allow-empty -m first
git branch --show-current
git rev-parse --abbrev-ref HEAD
git checkout -q --detach
echo "detached: [$(git branch --show-current)]"
git rev-parse --abbrev-ref HEADmain
main
detached: []
HEADgit branch --show-current, added in Git 2.22, prints the short name of the current branch or an empty line in a detached state, as the git-branch manual says. That makes [ -z "$(git branch --show-current)" ] a clean test for detached HEAD. The older rev-parse --abbrev-ref HEAD prints the literal word HEAD there, which is easy to mistake for a branch called HEAD.
Before Git 2.22 use git symbolic-ref --short -q HEAD, which exits non-zero on a detached HEAD. In a repository with no commits, rev-parse --abbrev-ref HEAD fails, while --show-current already prints the name of the unborn branch.