在 bash 脚本中发送邮件输出文字 \n 而不是新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32779781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending mail in bash script outputs literal \n instead of a new line
提问by Grant
I am using the following bash script to send an email
我正在使用以下 bash 脚本发送电子邮件
#!/bin/bash
recipients="[email protected], [email protected]"
subject="Just a Test"
from="[email protected]"
message_txt="This is just a test.\n Goodbye!"
/usr/sbin/sendmail "$recipients" << EOF
subject:$subject
from:$from
$message_txt
EOF
But when the email arrives the $message_txt content is printed literally like this :
但是当电子邮件到达时,$message_txt 的内容是这样打印的:
This is just a test.\n Goodbye!
Instead of interpreting the new line like this :
而不是像这样解释新行:
This is just a test.
Goodbye!
I've tried using :
我试过使用:
echo $message_txt
echo -e $message_txt
printf $message_txt
But the result is always the same. Where am I going wrong?
但结果总是一样的。我哪里错了?
What am I doing wrong?
我究竟做错了什么?
采纳答案by deimus
In bash you should use following syntax
在 bash 中,您应该使用以下语法
message_txt=$'This is just a test.\n Goodbye!'
message_txt=$'This is just a test.\n Goodbye!'
Single quotes preceded by a $
is a new syntax that allows to insert escape sequences in strings.
以 a 开头的单引号$
是一种允许在字符串中插入转义序列的新语法。
Check following documentationabout the quotation mechanism of bash
for ANSI C-like escape sequences
检查以下有关ANSI C 类转义序列的引用机制的文档bash
回答by chepner
You can also embed newlines directly in a string, without an escape sequence.
您还可以直接在字符串中嵌入换行符,而无需转义序列。
message_txt="This is just a test.
Goodbye!"