如何使用mailx命令格式化bash脚本中的邮件内容
解决mailx发送邮件内容前导多余空格的问题
方法1:直接移除字符串内的前导空格
你当前的问题根源是echo的字符串里手动加了缩进空格,直接删掉这些空格就能解决:
echo "Hello there, Please find the attachment. Email content is having spaces between the lines. I want the spaces to be removed. Thanks" | mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com"
方法2:用sed过滤前导空格(适合需保留脚本缩进的场景)
如果脚本里为了可读性需要保留代码缩进,可以在管道中加入sed命令,自动移除每行开头的所有空格:
echo "Hello there, Please find the attachment. Email content is having spaces between the lines. I want the spaces to be removed. Thanks" | sed 's/^[[:space:]]*//' | mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com"
解释:^[[:space:]]*匹配行首的任意数量空格(包括制表符),s/...//把匹配到的内容替换为空。
方法3:用Here-document(更优雅的脚本写法)
用<<-EOF的Here-document语法,脚本里可以用制表符缩进内容,该语法会自动移除每行前的制表符,既保证脚本可读性,又输出干净的邮件内容:
mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com" <<-EOF Hello there, Please find the attachment. Email content is having spaces between the lines. I want the spaces to be removed. Thanks EOF
注意:这里内容前的缩进必须是制表符(Tab),不能是空格,否则<<-EOF不会生效。
内容的提问来源于stack exchange,提问作者Sherin Shaziya
相关产品推荐
相关产品推荐

