Bash – How to get first 5 chars of a git commit hash id and store it in a variable in bash

bashgit

${$(git rev-parse HEAD):0:5}
bash: ${$(git rev-parse HEAD):0:5}: bad substitution

git rev-parse HEAD returns the hash id, but how do I make a substring out of it?

if I divide it into two lines, it works.

x=$(git rev-parse HEAD)
echo ${x:0:5}

But How do I do it in one line?

Best Answer

Using --short option:

$ git rev-parse --short=5 HEAD
90752

$ x=$(git rev-parse --short=5 HEAD)
$ printf '%s\n' "$x"
90752
Related Question