【问题标题】:Removing Leading 0 from a number causes value to change [duplicate]从数字中删除前导 0 会导致值更改 [重复]
【发布时间】:2021-10-11 23:34:05
【问题描述】:

我不明白这里发生了什么,基于Convert string into integer in bash script - "Leading Zero" number error,我能够将字符串转换为整数。我什至可以做加法。但是,当我比较数字时,它给了我错误的比较。参考下面的例子

这是一个例子

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
    do
        if [[ ${array[i]#0} > 15 ]]
        then
            echo "${array[i]#0} is greater than 15"
        else
            echo "${array[i]#0} is less than 15"
        fi
done

输出

2 is greater than 15
8 is greater than 15
10 is less than 15
11 is less than 15
23 is greater than 15
52 is greater than 15

【问题讨论】:

  • 我建议将 > 替换为 -gt 进行算术测试。
  • 这能回答你的问题吗? How can I compare numbers in Bash? - 领先的 0 在这里不是问题,因为您的值不会以八进制更改;这完全是关于字典式字符串排序中“15”与“2”的位置。
  • @dawg 是的,这帮了很多忙,我从来不知道有这么大的区别。谢谢!

标签: bash


【解决方案1】:

要么将[[ ]] 更改为(( )) 以使用>,要么将运算符更改为-gt 以在[[ ]] 内部进行整数比较

第一:

#!/bin/bash

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
do
    if (( ${array[i]#0} > 15 ))
    then
        echo "${array[i]#0} is greater than 15"
    else
        echo "${array[i]#0} is less than 15"
    fi
done

第二:

#!/bin/bash

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
do
    if [[ ${array[i]#0} -gt 15 ]]
    then
        echo "${array[i]#0} is greater than 15"
    else
        echo "${array[i]#0} is less than 15"
    fi
done

如果您在[ ] 或[[ ]] 中使用< > ==,则为string comparison operator。字符串"02"实际上小于字符串"15":

% [[ 02 > 15 ]]; echo $?
1                        # '1' means false and '0' means true

但是您正在用#0 剥离领先的"0":

% s="02"
% echo ${s#0}
2

所以现在您将 STRING "2" 与 STRING "15" 进行比较:

% [[ 2 > 15 ]]; echo $?
0 
% [[ ${s#0} > 15 ]]; echo $?
0

这给出了您所看到的令人惊讶的结果......

更多示例请参见this answer。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2011-11-28
    • 1970-01-01
    • 2011-10-04
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多