在bash中格式化电子邮件输出

时间:2018-07-09 20:47:10

标签: bash

我正在编写一个脚本,该脚本在用户的AWS访问密钥过旧时向其发送电子邮件。

现在输出看起来像这样:

Hello tdunphy, \n Your access key: AKIAICDOHVTMEAB6RM5Q was created on Wed Feb  7 22:55:51 EST 2018 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days. \n Regards, \n Cloud Ops

我希望消息看起来像这样:

Hello tdunphy,

 Your access key: AKIAICDOHVTMEAB6RM5Q was created on Wed Feb  7 22:55:51 EST 2018 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days.

Regards,
Cloud Ops

这是设置邮件正文的行:

 MAIL_TXT1="Hello $user_name, \\n Your access key: $user_access_key1 was created on $date1 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days. \\n Regards, \\n Cloud Ops"

在此示例中,为什么换行符不起作用?我该如何使用它?

1 个答案:

答案 0 :(得分:0)

您可以使用:

template=$'Hello tdunphy, \n Your access key: AKIAICDOHVTMEAB6RM5Q was created on Wed Feb  7 22:55:51 EST 2018 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days. \n Regards, \n Cloud Ops'

然后echo起作用:

$ echo "$template"
Hello tdunphy, 
 Your access key: AKIAICDOHVTMEAB6RM5Q was created on Wed Feb  7 22:55:51 EST 2018 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days. 
 Regards, 
 Cloud Ops

printf

$ printf "%s" "$template"
 Your access key: AKIAICDOHVTMEAB6RM5Q was created on Wed Feb  7 22:55:51 EST 2018 and needs to be replaced. All AWS Keys need to be replaced if they are older than 90 days. 
 Regards, 
 Cloud Ops

借助printf,您还可以更轻松地组装模板字段:

$ t2=$'Fields:\n\tf1=%s\n\tf2=%s'
$ printf "$t2" 101 102
Fields:
    f1=101
    f2=102