My Git repository is in a state where HEAD
might be a branch, or it might be a detached head. In a script, I want to get the current value such that I can reliably restore it with git checkout
later: that is, if we're on a branch now, I want to come back to that branch, not to a detached head of that commit. What's the easiest way to get that information, without having to deal with the two cases separately in my script?
Asked
Active
Viewed 20 times
0

Dan Hulme
- 14,779
- 3
- 46
- 95
1 Answers
3
git symbolic-ref --short -q HEAD || git show-ref -s HEAD
The first arm of the command prints out the name of the branch HEAD
points to, or silently fails. In the fail case, the second arm of the command prints out the commit that HEAD
points to.

Dan Hulme
- 14,779
- 3
- 46
- 95