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. 所以,如果你也有这样的想法来缩短代码,那就太棒了!

谢谢!

4

1 回答 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.
于 2019-02-27T02:12:12.267 回答