我有帶有 If 條件的 For 回圈,但它不能正常作業。它假設檢查每個索引值,如果 < 255 則顯示有效,否則無效。第三和第四不正確。
如何解決這個問題?
listNumber=(25 255 34 55)
listLength=${#listNumber[@]}
isValid=0
for ((index=0; index<$listLength; index )); do
itemNumber="$((index 1))"
if [[ ${listNumber[$index]} < 255 ]]; then
echo -e "Item $itemNumber : ${listNumber[$index]} is Valid. \n"
isValid=1
else
echo -e "Item $itemNumber : ${listNumber[$index]} is NOT Valid. \n"
fi
done
Result:
Item 1 : 25 is Valid.
Item 2 : 255 is NOT Valid.
Item 3 : 34 is NOT Valid.
Item 4 : 55 is NOT Valid.
uj5u.com熱心網友回復:
不幸的是,<在里面使用的時候[[...]]會使用字串比較:
當與 [[ 一起使用時,'<' 和 '>' 運算子使用當前語言環境按字典順序排序。
來源:https ://www.gnu.org/software/bash/manual/bash.html#index-commands_002c-conditional
您可以使用適當的算術比較運算子,-lt在這種情況下是:
if [[ ${listNumber[$index]} -lt 255 ]]; then
fi
或者對條件使用算術背景關系,使用雙括號表示(類似于您撰寫for回圈的方式):
if (( ${listNumber[$index]} < 255 )); then
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449692.html
上一篇:迭代函式并連接結果
