【问题标题】:How to fix For Loop and If condition NOT working in Bash Script如何修复 For 循环和 If 条件在 Bash 脚本中不起作用
【发布时间】:2022-10-23 03:12:35
【问题描述】:

我有带有 If 条件的 For 循环,但它不能正常工作。 它假设检查每个索引值,如果 < 255 则显示有效,否则无效。 第三和第四不正确。

如何解决这个问题?

listNumber=(25 255 34 55)
listLength=${#listNumber[@]}
isValid=0

for ((index=0; index<$listLength; index++)); do
    itemNumber="$((index+1))"
    
    if [[ ${listNumber[$index]} < 255 ]]; then
        echo -e "Item $itemNumber : ${listNumber[$index]} is Valid. \n"
        isValid=1
    else
        echo -e "Item $itemNumber : ${listNumber[$index]} is NOT Valid. \n"
    fi
done

Result:
Item 1 : 25 is Valid. 

Item 2 : 255 is NOT Valid. 

Item 3 : 34 is NOT Valid. 

Item 4 : 55 is NOT Valid. 

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    不幸的是,&lt;[[...]] 中使用时将使用字符串比较:

    当与 [[ 一起使用时,“<”和“>”运算符使用当前语言环境按字典顺序排序。

    来源:https://www.gnu.org/software/bash/manual/bash.html#index-commands_002c-conditional

    您可以使用适当的算术比较运算符,在本例中为 -lt

    if [[ ${listNumber[$index]} -lt 255 ]]; then
    fi
    

    或者对条件使用算术上下文,使用双括号表示(类似于您编写 for 循环的方式):

    if (( ${listNumber[$index]} < 255 )); then
    fi
    

    【讨论】:

    • 非常感谢!感谢你的帮助 :)
    • @布鲁斯Q。很高兴能帮助你 :)
    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多