To get the name of the current branch, we can use git rev-parse:
gitrev-parse--abbrev-refHEAD
This will print the name of the current branch as long as we have one checked out. If we're in a detached HEAD state, it will print HEAD.
Since version 2.22, git branch has a --show-current option. It will give us the name of the current branch, but intead will print nothing if we're in a detached HEAD state.