在一个linuxsbash脚本中,我试图使用mailx为我读到的每一行文件发送一封电子邮件。read行包含构建电子邮件的参数。我可以在这个循环之外发送相同的电子邮件。谢谢你的意见。

#!/bin/bash
in_email_file='./in_file.txt'
email_adr="address@somewhere.com"

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|address@domain.com
subject2|body2|address@domain.com
subject3|body3|address@domain.com

最佳答案

您没有共享您试图在循环中运行的确切代码,但不管怎样,我怀疑这是bash脚本的一个occurrence of a common(令人沮丧)绊脚石。很可能,你在试图做一些有趣的事情。
tl;dr下面是如何避免reads内部reads:

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

总结一下:使用内置的read可以编写一个正常的mapfile循环。阅读陷阱页面,了解bash循环破坏大脑的不同方式。
*编辑:
注意,我没有运行这段代码,所以我会像平常一样回显行和调试(我在平板电脑上)。
另外,我漏掉了你的for电话,因为看起来你只是在用它来猫?但是如果你想要grep,就把它传递给grep这样:mapfile
mapfile -t lines < <(grep someExpression "$in_email_file")了解更多

10-06 15:42
查看更多