2

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.

Community
  • 1
  • 1
ducin
  • 25,621
  • 41
  • 157
  • 256

3 Answers3

4

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}
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Using sed:

git rev-parse HEAD | sed 's/^\(.\{,8\}\).*$/\1/g'
plesiv
  • 6,935
  • 3
  • 26
  • 34
0
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

Matt
  • 45,022
  • 8
  • 78
  • 119
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
  • 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` – nu11p01n73R Oct 11 '14 at 12:12