使用 if-else 在 Bash 中进行整数比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18161234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:02:30  来源:igfitidea点击:

Integer comparison in Bash using if-else

bashif-statement

提问by rahuL

I have a variable called choice. Now, I try to use if to compare the entered value:

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

read $choice

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

The output goes directly to invalid choice if I enter either 1 or 2. I tried to put quotes around 1 and 2 inside the if statement. Still didn't work. Using -eqgives me an error "Unary operator expected".What am I doing wrong here?

如果我输入 1 或 2,输出将直接进入无效选择。我试图在 if 语句中将 1 和 2 周围的引号括起来。还是没用。使用-eq给我一个错误“一元运算符预期”。我在这里做错了什么?

回答by Mat

Your readline is incorrect. Change it to:

你的read线路不正确。将其更改为:

read choice

i.e. use the name of the variable you want to set, not its value.

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

-eqis the correct test to compare integers. See man testfor the descriptions (or man bash).

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

An alternative would be using arithmetic evaluation instead (but you still need the correct readstatement):

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

read choice

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

回答by devnull

For your example, caseseems to be what you probably want:

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

read choice

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

回答by chepner

An unpractical answer, just to point out that since readtakes a variable name, the name can be specified by another variable.

一个不切实际的答案,只是为了指出,由于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 ))