I am looking for a simple way to pipe the result of md5sum into another command. Something like this:

$echo -n 'test' | md5sum | ...

My problem is that md5sum outputs not only the hash of the string, but also an hypen, which indicates that the input came from stdin. I checked the man file and I didn't find any flags to control output.

  • 4
    Note: be careful not to use echo -n when the text data is unknown. Use printf '%s' "$DATA" instead. Unlike echo -n "$DATA", it will work when DATA="-n" (among other examples). Aug 16 '11 at 22:57

You can use the command cut; it allows you to cut a certain character/byte range from every input line. Since the MD5 hash has fixed length (32 characters), you can use the option -c 1-32 to keep only the first 32 characters from the input line:

echo -n test | md5sum | cut -c 1-32

Alternatively, you can tell cut to split the line at the every space and output only the first field: (note the quotes around the space character)

echo -n test | md5sum | cut -d " " -f 1

See the cut manpage for more options.

  • I thought about that also! I chose -d+-f so that md5sum can be replaced with sha1sum or whatever later. Aug 16 '11 at 22:45
  • awk works too: echo -n test | md5sum | awk -F" " '{print $1}' or awk -F" " '{print $1}' <(echo -n test | md5sum)
    – laebshade
    Aug 16 '11 at 23:48
  • Thank you for the answer. @laebshade Actually, you have to use printf otherwise it will output a new line character at the end ;)
    – nmat
    Aug 17 '11 at 2:25
  • @laebshade: the -F" " option to awk is very strange to see, given that it is the default for awk.
    – enzotib
    Aug 17 '11 at 4:43

You can cut it:

echo -n 'test' | md5sum | cut -d' ' -f1

Here, -d' ' chooses space as delimiter, and -f1 asks for the first field (before a delimiter).


Using awk works fine too :

echo -n 'test' | md5sum | awk '{print $1}'

Another way is making a substring. Because you know md5 hash is a string with 32 characters, you could use :

HASH=$(echo -n 'test' | md5sum -) && echo ${HASH:0:32}

It's just string manipulations, so you got the choice !

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.