I'm trying to store the MD5 of a variable into another variable. Between backticks and the more modern () notation, I cannot figure out how to assign the value of a variable run through a command to another variable. Sample code:

backup_dir=$(date +%Y-%m-%d_%H-%M-%S)
hashed=$( ${backup_dir} | md5)

Here, the hashed variable doesn't work, it takes the literal string backup_dir and hashes that. So the hash is always the same. Any thoughts?


  • Did you mean hashed=$( echo ${backup_dir} | md5) ? – Stephen Harris Feb 18 at 15:00

You are expecting md5 to read the value of the backup_dir variable and return its MD5 hash sum.

The command pipeline

${backup_dir} | md5

would try to run $backup_dir as a command, piping its output to md5. I would expect a "command not found" error from this, along with the MD5 hash of the empty string (d41d8cd98f00b204e9800998ecf8427e) in $hashed.

Instead, you would need to use something like

printf '%s' "$backup_dir" | md5

to give md5 the value on its standard input stream.

You could also use echo "$backup_dir" | md5 or md5 <<<"$backup_dir", but note that this adds a newline to the end of the value of $backup_dir which would alter the hash.

If md5 is the md5 utility commonly found on BSD and BSD-like systems (e.g. macOS), then you should use

md5 -q -s "$backup_dir"

The -s option takes a string as its argument, and -q causes md5 to only print out the hash of that string and nothing else.


backup_dir=$(date +%Y-%m-%d_%H-%M-%S)
hashed=$(md5 -q -s "$backup_dir")
  • 1
    This works and looks clean. Thank you for the patient explanation! – Khom Nazid Feb 18 at 16:01

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.