Atomiklan
Atomiklan

Reputation: 5434

Greater than comparison gives inconsistent results in Bash

This script seems to give inconsistent results. For example, when the if statement sees its first string that is greater, it works fine. But, sometimes, later strings that are larger get ignored completely:

ITEM[0]="XX"
ITEM[1]="XXXXXXX"
ITEM[2]="X"
ITEM[3]="XXXXXXXXXXXX"
ITEM[4]="XXXX"

SETPOINT=0
for i in "${!ITEM[@]}"; do
        STRING="${ITEM[$i]}"
        LENGTH=${#STRING}
        echo "String length = $LENGTH"
        if [ $LENGTH \> $SETPOINT ]; then
                SETPOINT=$LENGTH
                echo "Setpoint was updated to $SETPOINT"
        fi
        echo "Loop again"
done
echo "Final setpoint = $SETPOINT"

Here is the example output:

String length = 2
Setpoint was updated to 2
Loop again

String length = 7
Setpoint was updated to 7
Loop again

String length = 1
Loop again

String length = 12 <--- Why didn't it catch this one?????
Loop again

String length = 4
Loop again

Final setpoint = 7

Also, originally I had tried to do the variable expansion and string counting inside the if statement, so I didn't have to create "STRING" and "LENGTH", but I could not figure out the syntax to both expand the array variable and count the string at same time inside the if. So, if you have a thought on that too in order to shorten the code, that would be amazing!

Thanks!

Upvotes: 1

Views: 63

Answers (1)

gromi08
gromi08

Reputation: 515

Replace the \> with -gt.

man test explains that:

 s1 > s2       True if string s1 comes after s2 based on the binary value of their characters.
 n1 -gt n2     True if the integer n1 is algebraically greater than the integer n2.

Upvotes: 1

Related Questions