Linux Bash。在读取文件行的while循环中发送mailx
问题描述:
在Linux bash脚本中,我尝试使用mailx为每个读取的文件行发送1封电子邮件。读取的行包含构建电子邮件的参数。我可以在此循环之外发送相同的电子邮件。感谢您的任何意见。Linux Bash。在读取文件行的while循环中发送mailx
#!/bin/bash
in_email_file='./in_file.txt'
email_adr="[email protected]"
while IFS='|' read -r subject body email
do
#these are echoed
echo "$subject"
echo "$body"
echo "$email"
#this does not get sent
echo "$body" | mailx -s "$subject" -r $email_adr $email
done < $in_email_file
#this gets sent
echo "Email body sent from outside loop" | mailx -s "Email subject sent from
outside loop" -r $email_adr $email_adr
读取输入文件看起来是这样的:
subject1|body1|[email protected]
subject2|body2|[email protected]
subject3|body3|[email protected]
答
你不同意你想在循环中运行确切的代码,但无论我怀疑这是一个occurrence of a common(令人沮丧的)与bash脚本绊脚石。很可能,你正试图在read
循环内做一些有趣的事情(即:陷阱的秘诀)。
TL;博士以下是如何避免内部read
小号read
S:
mapfile -t lines < "$in_email_file" # affectively one of the reads
for line in "${lines}";do #now no read occurs here
IFS=\| read subject body email < <(echo "$line")
# ... mailx thing you're doing
done
总结:使用内置mapfile
,所以你可以写一个正常for
循环。阅读这个陷阱页面,了解bash循环的不同方式可能会破坏你的大脑。
*编辑:
- 注意到我没有运行此代码,所以我回声线和调试正常(我在平板电脑)。
- 此外,我忘了你的
grep
电话,因为它似乎你只是用它来猫?但是如果你想给grep,只是把它传递给mapfile
这样:mapfile -t lines < <(grep someExpression "$in_email_file")
- 也
help mapfile
更多
你必须让输入文件,你的循环里面做什么的内容。 –
“寻求调试帮助的问题(”为什么这个代码不工作?“)必须包含所需的行为,特定的问题或错误以及在问题本身中重现问题所需的最短代码。对其他读者很有用,参见:[**如何创建一个最小,完整和可验证的示例**](http://*.com/help/mcve)。“ –