大于比较会在Bash中产生不一致的结果

问题描述 投票:2回答:1

这个脚本似乎给出了不一致的结果。例如,当if语句看到它的第一个字符串更大时,它可以正常工作。但是,有时候,较大的后续字符串会被完全忽略:

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"

以下是示例输出:

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

另外,最初我曾尝试在if语句中进行变量扩展和字符串计数,所以我不必创建“STRING”和“LENGTH”,但我无法弄清楚扩展数组变量和在if内同时计算字符串。所以,如果你也想到了这一点,以便缩短代码,这将是惊人的!

谢谢!

bash string-comparison
1个回答
1
投票

\>替换-gt

man test解释说:

 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.
© www.soinside.com 2019 - 2024. All rights reserved.