我有一個這樣的腳本:
while :
do
Start_Time=$(date +"%s")
MAIN PROGRAM GOES HERE (CROPPED TO SHORTEN THINGS)
Run_Time=$(( $(date +"%s") - $Start_Time ))
if [[ $Run_Time < $Wait_Time ]]
then
Delay_Time=$(( $Wait_Time - $Run_Time ))
sleep $Delay_Time
else
echo "Delay exceeded"
echo $Run_Time
echo $Wait_Time
fi
done
我的問題是,有時即使運行時間小於等待時間,它也會失敗 < 測試
這是上次運行的輸出:
Delay exceeded
Run_Time 4
Wait_Time 30
答案1
嘗試運行以下程式碼片段:
if [[ 5 < 20 ]]
then
echo "5 < 20, as expected"
else
echo "5 is not less than 20, but why?"
fi
輸出將是5 is not less than 20, but why?
.答案是您正在使用<
條件式運算符,其記錄如下:
字串 1 < 字串 2 如果在目前語言環境中 string1 按字典順序排序在 string2 之前,則為 true。
你的問題是“20”按字典順序(或基本上按字母順序)位於“5”之前。
您正在尋找:
if (( $Run_Time < $Wait_Time ))
相反 - 這使用算術評估和算術小於,這正是您所需要的。