我正在編寫這個 bash 腳本,它將讀取包含日期、時間和電話號碼的文件,並且它將使用簡訊提供者 API 發送簡訊提醒。
#!/bin/bash
while read date time phone
do
user=user
pass=pass
senderid=senderid
message=Your%20appointment%20is%20at%20$date%20$time.%20For%20cancellations%20call%2096989898.%20Thank%20you.
api="https://sms.service.com/Websms/sendsms.aspx?User=$user&passwd=$pass&mobilenumber=357$phone&message=$message&senderid=$senderid&type=0"
curl -k $api
done < ~/sms_reminders/events/events_$(date +%d-%m-%y)
當我像這樣運行它時,我立即收到一條短信。但我想安排提醒在特定時間出去。所以我把腳本改成這樣。
#!/bin/bash
while read date time phone
do
user=user
pass=pass
senderid=senderid
message=Your%20appointment%20is%20at%20$date%20$time.%20For%20cancellations%20call%2096989898.%20Thank%20you.
api="https://sms.service.com/Websms/sendsms.aspx?User=$user&passwd=$pass&mobilenumber=357$phone&message=$message&senderid=$senderid&type=0"
echo curl -k $api | at $time
done < ~/sms_reminders/events/events_$(date +%d-%m-%y)
我收到一條訊息說
warning: commands will be executed using /bin/sh
job 22 at Fri Jun 6 21:46:00 2019
這很好。
但我從來沒有收到過簡訊。
我的猜測是這個問題與 sh 有關,但我無法確定,因為 at 並沒有真正產生一個日誌檔案來說明命令是否成功完成。
答案1
您可以透過參數擴充來告訴 Bash 引用該api
變數:
${parameter@operator}
擴展要么是參數值的轉換,要么是參數本身的信息,具體取決於運算符的值。每個運算符都是一個字母:
Q
擴展是一個字串,它是以可重複用作輸入的格式引用的參數值。
所以:
echo curl -k "${api@Q}" | at "$time"
如果像 in 一樣轉義引號echo curl -k \"$api\"
,那麼 的擴展api
將進行字段分割和通配符擴展,這可能會導致問題,具體取決於內容。所以最好正常引用它"${api}"
,並告訴 bash 再次引用它以使用"${api@Q}"
.
作為參考,使用範例輸入,輸出為:
$ echo curl -k "${api@Q}"
curl -k 'https://sms.service.com/Websms/sendsms.aspx?User=user&passwd=pass&mobilenumber=357&message=Your%20appointment%20is%20at%20%20.%20For%20cancellations%20call%2096989898.%20Thank%20you.&senderid=senderid&type=0'
請注意輸出中 URL 周圍新增的單引號。
答案2
我不得不這樣做
echo curl -k \"$api\" | at $time