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
  • 24,243
  • 40
  • 145
  • 253

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
  • 713,503
  • 59
  • 514
  • 593
0

Using sed:

git rev-parse HEAD | sed 's/^\(.\{,8\}\).*$/\1/g'
plesiv
  • 6,908
  • 3
  • 24
  • 33
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
  • 42,566
  • 8
  • 67
  • 104
nu11p01n73R
  • 25,677
  • 2
  • 36
  • 50
  • 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