gpt4 book ai didi

linux - bash 脚本修改以从 echo 命令获取参数

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:11 24 4
gpt4 key购买 nike

我有this使用 mandril 发送电子邮件的小型 bash 脚本 (sendmail.sh)像这样使用时效果 super 好 ./sendmail.sh "my@email.com""Email Subject""Email body"。感谢black @ LET但是我希望这个脚本像 linux 邮件命令一样从 echo 命令获取它的电子邮件正文。 echo "邮件正文"| mail -s "邮件主题"email@any.com

当我将以下脚本与此命令一起使用时 echo "email body"|./sendmail.sh "my@email.com""Email Subject" 它会打印 else block 中指定的错误(因为只给出了 2 个参数但需要 3 个)/sendmail.sh 需要 3 个参数 - 地址、主题、内容
示例:././sendmail.sh "to-address@mail-address.com""test""你好,这是一条测试邮件"

惊讶地发现为什么 echo 命令输出没有被用作脚本中 $3 参数的输入。

#!/bin/bash
#created by black @ LET
#MIT license, please give credit if you use this for your own projects
#depends on curl

key="" #your maildrill API key
from_email="" #who is sending the email
reply_to="$from_email" #reply email address
from_name="curl sender" #from name


if [ $# -eq 3 ]; then
msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "return_path_domain": null, "subject": "'$2'", "text": "'$3'", "to": [ { "email": "'$1'", "type": "to" } ] } }'
results=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1);
echo "$results" | grep "sent" -q;
if [ $? -ne 0 ]; then
echo "An error occured: $results";
exit 2;
fi
else
echo "$0 requires 3 arguments - to address, subject, content";
echo "Example: ./$0 \"to-address@mail-address.com\" \"test\" \"hello this is a test message\""
exit 1;
fi

最佳答案

为什么令人惊讶?您正在混合参数和标准输入,这在根本上是完全不同的。

不过,满足这个要求并不难。

case $# in
3) text="$3" ;;
2) text=$(cat) ;;
esac
: .... do stuff with "$text"

您的脚本的缩进和引号有点草率,所以这里是一个稍微重构的版本。

key="" #your maildrill API key
from_email="" #who is sending the email
from_name="curl sender" #from name

case $# in
3) text="$3";;
2) text="$(cat)";;
*) echo "$0: oops! Need 2 or 3 arguments -- aborting" >&2; exit 1 ;;
esac

msg='{ "async": false, "key": "'"$key"'", "message": { "from_email": "'"$from_email"'", "from_name": "'"$from_name"'", "return_path_domain": null, "subject": "'"$2"'", "text": "'"$text"'", "to": [ { "email": "'"$1"'", "type": "to" } ] } }'
result=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1)
case $results in
*"sent"*) exit 0;;
*) echo "$0: error: $results" >&2; exit 2;;
esac

请特别注意任何用户提供的字符串绝对必须在双引号内。

(我去掉了 Reply-To: 因为当它等于 From: header 时它是完全多余的。)

关于linux - bash 脚本修改以从 echo 命令获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28479168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com