【问题标题】:Greater than comparison gives inconsistent results in Bash大于比较在 Bash 中给出不一致的结果
【发布时间】:2019-02-27 01:49:14
【问题描述】:

这个脚本似乎给出了不一致的结果。例如,当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 提示符下,键入 help [ 然后键入 help test -- &gt; 运算符执行 string 比较,它根据词汇(字典)顺序进行比较.有不同的运算符进行算术比较。

标签: bash string-comparison


【解决方案1】:

\&gt; 替换为-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.

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    相关资源
    最近更新 更多