简体   繁体   中英

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

There's a number of issues here.

  • You should generally quote strings. Without quoting, the string after < is split (hence the error message) and the array you took so much care to collect will lose its purpose.
  • The thing after < needs to be the name of a file. In Bash you can use a here string <<<"$MESSAGEx" but the common and simple portable solution is to echo (or better printf ) its value into a pipe.
  • You should prefer lower case for your private variable names, but this is mainly a stylistic recommendation. (There are reserved variables like PATH and SHELL which you really don't want to clobber; POSIX reserves upper case variable names for system use.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM