I apologize if this has already been answered, or if the answer is simpler than I realize, but I can't seem to figure out the following:

When I try to generate an md5 from a string, either with

echo -n "string" | md5sum | cut -f1 -d' '

or with

echo -n "string" | openssl md5

the result is not 32 characters, as I would expect, but rather 33 (using wc -c).

So, I have a few questions:

  1. Why do both md5sum and openssl add a trailing space?
  2. Is there another way to generate an md5 hash without a trailing newline or space?
  3. Does the trailing space really matter?

Thank you all in advance.

  • Instead of using awk like in the answer below i would use tr like this: echo -n "string" | md5sum | cut -d " " -f 1 | tr -d "\n" . This will clear the new line character from the output. – mnmnc Jan 9 '13 at 7:50

It's 32 characters! The md5sum is adding a linefeed to the end. You can get rid of it like this:

% echo -n string | md5sum|awk '{print $1}'|wc -c
% echo -n $(echo -n string | md5sum|awk '{print $1}')|wc -c

or you could do it like this:

% echo -n $(md5sum <<< 'string'|awk '{print $1}')|wc -c

You can tell when one of the commands is adding a newline because the 32 character string will show up on its own line. If no newline is present it should always show up like this:

[prompt %] echo -n $(md5sum <<< 'string'|awk '{print $1}')
b80fa55b1234f1935cea559d9efbc39a[prompt %]
  • Thanks for the answer! Unfortunately, I don't have enough reputation to vote you up. For the sake of clarity though, I think I like echo -n $(echo -n "string" | openssl md5) – Alex Krycek Jan 9 '13 at 5:12
  • 1
    Sure! That's the beauty of UNIX. There's more than one way to do everything! – slm Jan 9 '13 at 5:14

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.