Reputation: 585
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
Upvotes: 3
Views: 3074
Reputation: 487785
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.
Upvotes: 6
Reputation: 45659
The reason git prompt logic is usually wrapped up in a function is that it's not quite as simple as a single git command. You can get close with something like
git log -n 1 --format="%D>%h" |cut -d'>' -f2
but looking at this I can't help thinking it's a bit brittle (and you may get some unwanted white space).
The constraint of not using if
(or something equivalent) may not be entirely realistic here.
Upvotes: 0