大于比较在 Bash 中给出不一致的结果
Greater than comparison gives inconsistent results in Bash
这个脚本似乎给出了不一致的结果。例如,当 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
中同时扩展数组变量和计算字符串的语法。所以,如果你也有这样的想法以缩短代码,那将是惊人的!
谢谢!
将 \>
替换为 -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.
这个脚本似乎给出了不一致的结果。例如,当 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
中同时扩展数组变量和计算字符串的语法。所以,如果你也有这样的想法以缩短代码,那将是惊人的!
谢谢!
将 \>
替换为 -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.