Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show git branch name OR commit id

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. fish prompt

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 fish prompt

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

like image 995
MadStark Avatar asked Sep 13 '26 23:09

MadStark


1 Answers

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.

like image 139
torek Avatar answered Sep 16 '26 20:09

torek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!