I am trying to reproduce the behavior of my shell prompt when it comes to showing the current branch name.
I'm here using fish but most shell have this feature.

If I use the command
git rev-parse --abbrev-ref --verify HEAD
it returns me
master
Good!
Now, if I checkout an old commit, my prompt shows

And if I run the command above again it returns
HEAD
Which is not what I want. I want 3171f5a just like the prompt. So I've got a new command.
git rev-parse --short --verify HEAD
3171f5a
Nice! But if I come back to master it gives me
617ca76
Do you know if there's a command to give me that output straight away, without an if statement checking if the return value is HEAD.
(shorten hash or not is fine)
Thank you very much
The one-line way to do this in the shell is to use two separate Git commands:
git symbolic-ref --short -q HEAD || git rev-parse --short HEAD
In the detached HEAD case, the git symbolic-ref command fails (while the -q prevents it from complaining to stderr) and the second git rev-parse command goes on to print the shortened hash ID.
Note that when you are on an unborn branch, the git symbolic-ref command succeeds and you get the (shortened) name of the unborn branch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With