3

I have a passing understanding of Parameter Substitution, including substrings like so

foo="Hello World";
greeting=${foo:0:6}

But do I do this with commands?

greeting="Hello"
md5greeting=$(echo $greeting | md5sum :0:6)
>>b1946a

Where the output is the first 6 characters of the md5sum of the 'hello'.

How do I achieve this?

  • 1
    echo "$greeting" | md5sum | cut -c 1-6 would work if you know the output will only be a single line. – glenn jackman Oct 4 '18 at 14:37
5

Parameter substitution doesn't work like that, at least not in bash. You need a real variable (parameter) and directly operate on it. So for example like that:

var=$(echo abcdefgh | cmd1 | cmd2 | ... )
var2="${var:2:4}"

The exception is zsh where you can convert command substitution to parameter "on the fly" and do above in one line:

var2=${"$(echo abcdefgh | cdm1 | cmd2 | ... )":2:4}
4

Note that:

echo $greeting | md5sum

Or more reliably:

printf '%s\n' "$greeting" | md5sum

Does not give you the MD5 hash of the content of the variable, but of the content of the variable followed by a newline character. For the MD5 hash of the content of the variable:

printf %s "$greeting" | md5sum

For the first 6 bytes of it, with some head implementations:

printf %s "$greeting" | md5sum | head -c 6

or more portably:

printf %s "$greeting" | md5sum | dd bs=1 count=6 2> /dev/null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.