2016-09-28 36 views
2

我必須使用curl執行一個URL,如果輸出包含「hello」字符串,那麼我將成功退出shell腳本,否則我會一直重試直到上午8點如果它仍然不包含該字符串,則會返回錯誤消息。在一天之內的特定時間段內調用curl

我得到了下面的腳本,但我無法理解我如何可以運行while循環到上午8點,如果仍然捲曲輸出不包含「你好」字符串?

#!/bin/bash 

while true 
do 
    curl -s -m 2 "some_url" 2>&1 | grep "hello" 
    sleep 15m 
done 

所以,如果它是下午3點後,然後開始製作捲曲調用,直到上午8點,如果它與錯誤訊息上午8點退出成功後與捲曲電話給「你好」的字符串,成功退出,否則。

如果是在下午3點之前,它會保持睡眠,直到它通過下午3點。

我必須在腳本中添加這個邏輯,我不能在這裏使用cron。

回答

1

您可以使用腳本如下,GNU date

#/bin/bash 

retCode=0          # Initializing return code to of the piped commands 
while [[ "$(date +"%T")" < '08:00:00' ]];  # loop from current time to next occurence of '08:00:00' 
do 
    curl -s -m 2 "some_url" 2>&1 | grep "hello" 
    retCode=$?         # Storing the return code 
    [[ $retCode ]] && break     # breaking the loop and exiting on success   
    sleep 15m         
done 

[[ $retCode -eq 1 ]] && echo "String not found" >> /dev/stderr # If the search string is not found till the last minute, print the error message 
+0

測試在這種情況下,它會不斷循環在while循環,直到上午8點是正確的?我們能否儘快退出?如果不成功,那麼請繼續嘗試到上午8點,然後以非零狀態碼退出並顯示錯誤消息? – user1950349

+0

@ user1950349:請參閱我的更新,完成所做的更改以成功退出,並在錯誤消息已打印失敗時引用最後一行。 – Inian

+0

一個基本的東西,而不是在while循環中使用'break',如果我使用'exit 0',那麼它會是同樣的事情?並且在最後一行中,如果我必須退出非零狀態代碼(例如「退出2」)並輸出錯誤消息,那麼我們將如何執行此操作? – user1950349

1

我認爲您可以使用date +%k來檢索當前小時,並與上午8點和下午13點進行比較。代碼可能會喜歡這個

hour=`date +%k` 
echo $hour 
if [[ $hour -gt 15 || $hour -lt 8 ]]; then 
    echo 'in ranage' 
else 
    echo 'out of range' 
fi 
相關問題