使用if-else在Bash中进行整数比较 [英] Integer comparison in Bash using if-else
问题描述
我有一个名为 choice
的变量。现在,我尝试使用if来比较输入的值:
I have a variable called choice
. Now, I try to use if to compare the entered value:
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
给我一个错误一元运算符预期。我在这里做错了什么?
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 -eq
gives me an error "Unary operator expected".What am I doing wrong here?
推荐答案
您的读取
行不正确。将其更改为:
Your read
line is incorrect. Change it to:
read choice
即使用你想要设置的变量的名称,而不是它的值。
i.e. use the name of the variable you want to set, not its value.
-eq
是正确的测试比较整数。有关描述,请参阅 man test
(或 man bash
)。
-eq
is the correct test to compare integers. See man test
for the descriptions (or man bash
).
替代方案是使用算术评估(但您仍需要正确的读取
语句):
An alternative would be using arithmetic evaluation instead (but you still need the correct read
statement):
read choice
if (( $choice == 2 )) ; then
echo 2
elif (( $choice == 1 )) ; then
echo 1
else
echo "Invalid choice!!"
fi
这篇关于使用if-else在Bash中进行整数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!