我有以下用于发送电子邮件报告的bash脚本。我试图让它在bash上使用mail命令正常工作,并希望使用需要使用eval的变量替换条件。
#!/bin/bash
LOG="/tmp/error.txt"
echo "test" > $LOG
INCLUDED="aaaaaaaaaaaaaaaaa"
EXCLUDED="bbbbbbbbbbbbbbbbb"
STR=INCLUDED
BODY="
Email Body:
\${!STR}"
#Set STR based on some condition
STR=EXCLUDED # set conditional with if statement
SUB="email subject"
PARAMS="-r \" Sender <ret@address.com>\""
PARAMS+=" -s \"$SUB\""
PARAMS+=" -A $LOG" # use conditional with if statement
eval echo \"MESSAGE: "${BODY}"\" | mail $(eval echo ${PARAMS}) "user@email.com"
在运行下面的代码时,我必须传递$ PARAMS输出,而不是字符串周围的引号作为mail命令的输入,它不识别diff选项。我最接近的是使用调用$(eval echo $PARAMS)
,但这会使主题变得无聊,因为它删除了主题周围的双引号。
+ LOG=/tmp/error.txt
+ echo test
+ INCLUDED=aaaaaaaaaaaaaaaaa
+ EXCLUDED=bbbbbbbbbbbbbbbbb
+ STR=INCLUDED
+ BODY='
Email Body:
${!STR}'
+ STR=EXCLUDED
+ SUB='email subject'
+ PARAMS='-r " Sender <ret@address.com>"'
+ PARAMS+=' -s "email subject"'
+ PARAMS+=' -A /tmp/error.txt'
+ eval echo '"MESSAGE:' '
Email Body:
${!STR}"'
++ echo 'MESSAGE:
Email Body:
bbbbbbbbbbbbbbbbb'
++ eval echo -r '"' Sender '<ret@address.com>"' -s '$SUB' -A /tmp/error.txt
+++ echo -r ' Sender <ret@address.com>' -s email subject -A /tmp/error.txt
+ mail -r Sender '<ret@address.com>' -s email subject -A /tmp/error.txt user@email.com
如何将主题(-s)作为带引号的字符串传递给$ PARAMS传递给mail命令?
答案 0 :(得分:0)
使用数组代替并将每个字符串放在数组元素中。
params=('-r')
params=("${params[@]}" ' Sender <ret@address.com>')
mail "${params[@]}"
或更简单
params=('-r')
params+=(' Sender <ret@address.com>')
mail "${params[@]}"
见这里:Bash: add value to array without specifying a key
更新,因为我认为你缺乏一些基本的shell编程知识。
eval
!如果您需要延迟评估,请在调用时编写一个执行评估的函数。这是根据上述规则更新的示例。
LOG=/tmp/error.txt
echo 'test' > $LOG
INCLUDED='aaaaaaaaaaaaaaaaa'
EXCLUDED='bbbbbbbbbbbbbbbbb'
STR=INCLUDED
body () { echo "
Email Body:
$STR"
}
#Set STR based on some condition
STR=EXCLUDED # set conditional with if statement
SUB='email subject'
PARAMS=('-r' 'Sender <ret@address.com>')
PARAMS+=('-s' "$SUB")
PARAMS+=('-A' "$LOG") # use conditional with if statement
{ echo -n 'MESSAGE: '; body; } | mail "${PARAMS[@]}" 'user@email.com'
您可以通过在程序开头放置一个邮件模型来测试您的代码。
mail() { echo mail "$@"; cat; }