Programmatically check if HEAD is detached?
Asked Answered
A

4

20

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?

Allister answered 7/9, 2018 at 11:23 Comment(4)
See #6976973Optometrist
You can try git rev-parse --symbolic-full-name HEAD, if it outputs HEAD, you're in detached mode, if it outputs a branch name, you're on that branch.Optometrist
git rev-parse --abbrev-ref HEAD will give you a branch name if you're on a branch else will give you the detached HEAD hashPegpega
@Pegpega In detached HEAD state git rev-parse --abbrev-ref HEAD gives just "HEAD" string for me, not a hash.Maris
R
21

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.
Ridings answered 7/9, 2018 at 12:7 Comment(1)
Great solution. I'll just take this one.Allister
H
9

Programmatically check requires a wrapper for Git protocol.

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

Hydrargyrum answered 7/9, 2018 at 11:35 Comment(2)
I didn't mention what language I'm programming in. It could be Bash where the only interface is the git binary. And that's good - Once you know how to do it in Bash you can do it in any language - by calling git binary.Allister
@Allister git symbolic-ref HEAD may help you and just indicate the fatal error by grep command.Hydrargyrum
I
3

From git 2.22, you can also use:

git branch --show-current

This prints nothing when not on a branch.

Interrelation answered 14/3, 2022 at 10:34 Comment(0)
B
1

Use git branch to find a detached HEAD...

$ git branch -q
* (HEAD detached at c61a6d2)
  master
Bice answered 28/11, 2020 at 14:40 Comment(2)
Are you sure this output is ready for consumption (i.e. text parsing)?Allister
Sure enough to use it in my git wrapper. Could git change output? Yes, but vulnerabiity to bit-rot is common to any code you write. If you're worried, write a unit test...Bice

© 2022 - 2024 — McMap. All rights reserved.