ducin
ducin

Reputation: 26477

bash substring - combine command and slicing

I want to get first 8 characters of latest git commit hash. To retrieve git HEAD hash, I use git rev-parse HEAD. I've found here that I can get a substring using ${string:position:length}. But I don't know how to combine them both (in a one-liner, if possible). My attempt

${"`git rev-parse HEAD`":0:8}

is wrong.

Upvotes: 2

Views: 351

Answers (3)

nu11p01n73R
nu11p01n73R

Reputation: 26667

out=`git rev-parse HEAD`
sub=${out:0:8}

example:
a="hello"
b=${a:0:3}
bash-3.2$ echo $b
hel

its a two step process, where first the output of git command is extracted, which is a string. ${string:pos:len will return the substring from pos of length len

Upvotes: 0

plesiv
plesiv

Reputation: 7028

Using sed:

git rev-parse HEAD | sed 's/^\(.\{,8\}\).*$/\1/g'

Upvotes: 0

anubhava
anubhava

Reputation: 785691

You cannot combine BASH substring directive by calling a command inside it:

Instead you can use:

head=$(git rev-parse HEAD | cut -c1-8)

Or else old faishon 2 steps:

head=$(git rev-parse HEAD)
head=${head:0:8}

Upvotes: 4

Related Questions