【问题标题】:Integer comparison in Bash using if-else使用 if-else 在 Bash 中进行整数比较
【发布时间】:2013-08-10 11:02:20
【问题描述】:

我有一个名为choice 的变量。现在,我尝试使用 if 来比较输入的值:

read $choice

if [ "$choice" ==  2  ];then
       #do something
elif [ "$choice" == 1 ];then
       #do something else
else
     echo "Invalid choice!!"
fi

如果我输入 1 或 2,输出将直接进入无效选择。我尝试在 if 语句中将 1 和 2 放在引号内。仍然没有工作。使用-eq 给我一个错误“应为一元运算符”。我在这里做错了什么?

【问题讨论】:

    标签: bash if-statement


    【解决方案1】:

    您的read 行不正确。将其更改为:

    read choice
    

    即使用您要设置的变量的名称,而不是其值。

    -eq 是比较整数的正确测试。有关说明,请参阅 man test(或 man bash)。

    另一种方法是使用算术评估(但您仍然需要正确的 read 语句):

    read choice
    
    if (( $choice == 2 )) ; then
        echo 2
    elif (( $choice == 1 )) ; then
        echo 1
    else
        echo "Invalid choice!!"
    fi
    

    【讨论】:

    • 现在我觉得自己完全傻了。 :( 感谢您的帮助(以及快速回复),Mat!
    • 你的意思是“它的”价值;如果“它是”听起来不对,那么“它是”就不是
    • 感谢@Arthur,已修复。
    • 嗯,用 BusyBox sheel 处理和粘贴它似乎失败了。例如,当我输入 2 进行选择时,我得到错误... -ash: 2: not found -ash: 2: not found 有什么想法吗?
    • ash 不是 bash。试试 devnull 的 case 变体,它更便携。
    【解决方案2】:

    对于您的示例,case 似乎是您可能想要的:

    read choice
    
    case "$choice" in
    "1")
        echo choice 1;
        ;;
    "2")
        echo choice 2;
        ;;
    *)
        echo "invalid choice"
        ;;
    esac
    

    【讨论】:

      【解决方案3】:

      一个不切实际的答案,只是指出由于read采用了一个变量名,该名称可以由另一个变量指定。

      choice=choice   # A variable whose value is the string "choice"
      read $choice    # $choice expands to "choice", so read sets the value of that variable
      if [[ $choice -eq 1 ]]; then   # or (( choice == 1 ))
      

      【讨论】:

        猜你喜欢
        • 2011-05-25
        • 1970-01-01
        • 2011-01-29
        • 2017-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多