簡體   English   中英

bash腳本修改以從echo命令獲取參數

[英]bash script modify to take parameter from echo command

我有這個小bash腳本(sendmail.sh)發送電子郵件使用頂桿像這樣使用時的工作原理超級./sendmail.sh "my@email.com" "Email Subject" "Email body" 感謝black @ LET,但是我希望這個腳本像Linux mail命令一樣從echo命令獲取其電子郵件正文。 echo "email body" | mail -s "email subject" email@any.com

當我在此命令中使用以下腳本時, echo "email body" |./sendmail.sh "my@email.com" "Email Subject"它會打印在else塊中指定的錯誤(因為僅給出了2個參數,但需要3個參數) /sendmail.sh requires 3 arguments - to address, subject, content Example: ././sendmail.sh "to-address@mail-address.com" "test" "hello this is a test message"

驚奇地發現為什么在腳本中沒有將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:頭時,它是完全多余的。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM