15

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.

1
  • 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). Commented Aug 16, 2011 at 22:57

3 Answers 3

15

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.

4
  • I thought about that also! I chose -d+-f so that md5sum can be replaced with sha1sum or whatever later. Commented Aug 16, 2011 at 22:45
  • awk works too: echo -n test | md5sum | awk -F" " '{print $1}' or awk -F" " '{print $1}' <(echo -n test | md5sum) Commented Aug 16, 2011 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 ;) Commented Aug 17, 2011 at 2:25
  • @laebshade: the -F" " option to awk is very strange to see, given that it is the default for awk. Commented Aug 17, 2011 at 4:43
3

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).

2

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 !

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.