How do I echo a string to a file and call a function to hash it in the same function?

I'm trying to create a function where I pass in 2 variables. First a string to be hashed, and then a variable to specify the kind of hash, md5 or sha1. This is the function I created:

hashedWord () {
    echo $1 > pw.txt && $2 pw.txt | cut -d ' ' -f 1 
} > Desktop/hashedWord.txt

It is run as:

hashedWord aStringToHash, md5sum

where aStringToHash is the $1 variable and md5sum (a hashing variable) is $2.


You have several issues:

  • echo is error-prone; especially for strings you don't control it is better use printf.
  • Your variables are not quoted. --> printf '%s' "$1"
  • You save the password in cleartext to a file. Why ??? You should pipe to your hashing algorithm directly or you'll expose your password.
  • If you do that, you don't need echo or printf at all, you can use a here-string --> <<< "$1"
  • If you want, you could use tee file instead of > file to see the output on screen also.
  • Desktop/hashedWord.txt is a relative path. If you're not in ~, this will likely throw an error. Use an absolute path, e.g. ~/Desktop/hashedWord.txt.

--->

hashedWord() {
    "$2" <<< "$1" | cut -d ' ' -f1 | tee ~/Desktop/hashedWord.txt
}