Programmatically check if HEAD is detached?

The easiest command is probably:

$ git symbolic-ref -q HEAD

and check the exit status: 0 means normal; 1 is detached.

From the docs of git-symbolic-ref:

-q, --quiet
   Do not issue an error message if the <name> is not a symbolic ref
   but a detached HEAD; instead exit with non-zero status silently.

Programmatically you need to a wrapper for Git protocol.

For example, by GitPython you're able to find out the repo detached or not repo.head.is_detached


Use git branch to find a detached HEAD...

$ git branch -q
* (HEAD detached at c61a6d2)
  master