Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically check if HEAD is detached?

I want to know whether I'm in a "HEAD detached" state in a script.

Currently I parse the output of git status but I dislike doing so because I've heard that it's a bad practice to parse Git output that's meant for human - I want a program-friendly interface to tell me whether HEAD is detached. I also don't want to manually look into .git/HEAD or parse git description or git branch.

Any ideas?

like image 703
iBug Avatar asked Sep 07 '18 11:09

iBug


3 Answers

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.
like image 68
rodrigo Avatar answered Oct 20 '22 14:10

rodrigo


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

like image 8
Masoud Avatar answered Oct 20 '22 14:10

Masoud


Use git branch to find a detached HEAD...

$ git branch -q
* (HEAD detached at c61a6d2)
  master
like image 1
Mike Pennington Avatar answered Oct 20 '22 15:10

Mike Pennington