0

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. 

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Appreciate your help :)
@BruceQ. happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.