I have that For Loop with If condition but it's Not working correctly. It supposes to check each index value if < 255 display Valid else Not Valid. The third and Forth are not correct.
How to fix that issue?
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.
CodePudding user response:
Unfortunately, <
when used inside [[...]]
will use string comparison:
When used with [[, the ‘<’ and ‘>’ operators sort lexicographically using the current locale.
Source: https://www.gnu.org/software/bash/manual/bash.html#index-commands_002c-conditional
You either use the appropriate arithmetic comparison operator, which is -lt
in this case:
if [[ ${listNumber[$index]} -lt 255 ]]; then
fi
Or use an arithmentic context for the condition, which is denoted using double parentheses (similar to how you've written the for
loop):
if (( ${listNumber[$index]} < 255 )); then
fi