linuxbashemaildebian-stretch

Inserting the date into a "MAIL" message body in a BASH script


I have a relatively simple BASH script to send mail from my Raspberry Pi. The first argument is the Subject line and the second is a string of data files to be attached.

It is basically working when I specify the message body as a file (line 6). But if I try to create a text sting containing the date as the message body it fails (line7). Here is my script:

#!/bin/bash
#echo $2
# To
TO="me@hotmail.com"
# Message
MESSAGE="output/MessageBody.txt"
MESSAGEx="Midnight `date '+%Y-%m-%d %H:%M:%S %Z'` Pi report"
echo $MESSAGE
echo $MESSAGEx

temp=$(echo $2 | tr ";" "\n")
declare -a attargs
for att in $temp; do
  attargs+=( "-A"  "$att" )
done
# Sending email using /bin/mail
/usr/bin/mail -s "$1" "$TO" ${attargs[@]}  < $MESSAGEx

Here is the output from this command

/usr/pgms/sendtome.sh "test message" "/mnt/usbdrive/output/JSONstart.txt;/mnt/usbdrive/output/Outback_error.log;/mnt/usbdrive/output/OutbackReaderPrint.txt"

when I specify MESSAGEx as the message body:

/mnt/usbdrive/output/MessageBody.txt

Midnight 2019-08-14 07:40:31 MDT Pi report

/usr/pgms/sendtome.sh: line 22: $MESSAGEx: ambiguous redirect

If I use MESSAGE, ie the text file reference, it works. How can it create a message body text paragraph which contains the date or some other item? Thanks....RDK


Solution

  • There's a number of issues here.

    Here's a refactoring which attempts to address these concerns.

    #!/bin/bash
    to="me@hotmail.com"
    # Message
    #msgfile="output/MessageBody.txt"
    msgbody="Midnight `date '+%Y-%m-%d %H:%M:%S %Z'` Pi report"
    #echo "$msgfile"
    #echo "$msgbody"
    
    declare -a attargs
    for att in $(echo "$2" | tr ";" "\n"); do
      attargs+=( "-A"  "$att" )
    done
    
    /usr/bin/mail -s "$1" "${attargs[@]}" "$to"<<< "$msgbody"
    

    Perhaps a better design would be to just shift the first argument and then use "$@" as the list of files to attach.