[英]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. 我有一个相对简单的BASH脚本,用于从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). 当我将消息正文指定为文件时(第6行),它基本上可以正常工作。 But if I try to create a text sting containing the date as the message body it fails (line7).
但是,如果我尝试创建一个包含日期作为消息正文的文本字符串,它将失败(第7行)。 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: 当我将MESSAGEx指定为消息正文时:
/mnt/usbdrive/output/MessageBody.txt
/mnt/usbdrive/output/MessageBody.txt
Midnight 2019-08-14 07:40:31 MDT Pi report
午夜2019-08-14 07:40:31 MDT Pi报告
/usr/pgms/sendtome.sh: line 22: $MESSAGEx: ambiguous redirect
/usr/pgms/sendtome.sh:第22行:$ MESSAGEx:歧义重定向
If I use MESSAGE, ie the text file reference, it works. 如果我使用MESSAGE(即文本文件引用),它将起作用。 How can it create a message body text paragraph which contains the date or some other item?
如何创建包含日期或其他项目的邮件正文文本段落? Thanks....RDK
谢谢.... RDK
There's a number of issues here. 这里有很多问题。
<
is split (hence the error message) and the array you took so much care to collect will lose its purpose. <
之后的字符串(因此会出现错误消息),并且您非常注意收集的数组将失去其目的。 <
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. <<<"$MESSAGEx"
但是常见且简单的可移植解决方案是将其值echo
(或更好的printf
)到管道中。 PATH
and SHELL
which you really don't want to clobber; POSIX reserves upper case variable names for system use.) PATH
和SHELL
,您确实不想破坏; POSIX保留大写的变量名供系统使用。) 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. 也许更好的设计是仅
shift
第一个参数,然后使用"$@"
作为要附加的文件列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.