bash 参数过多 [if 语句]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33090357/
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
Too many arguments [if statements]
提问by Kyler
So everything in my code works, all but the multiplication one(*)
所以我的代码中的所有内容都有效,除了乘法 one(*)
ex4.sh: line 23: [: too many arguments
ex4.sh: line 26: [: too many arguments
ex4.sh: line 29: [: too many arguments
ex4.sh: line 32: [: too many arguments
Heres the script it asks you for a 2 numbers entered separately then an operation + being addition - being subtraction / being division and * being multiplication. Everything works all but multiplication which gives a too many arguments error
这是脚本,它要求您分别输入 2 个数字,然后进行运算 + 加法 - 减法 / 除法和 * 乘法。一切正常,但乘法会产生太多参数错误
echo First number
read NUM1
if ! [[ "$NUM1" =~ ^[0-9]+$ ]]; then
echo Integers only please
else
echo Second number
read NUM2
if ! [[ "$NUM2" =~ ^[0-9]+$ ]]; then
echo Integers only please
else
echo What operation would you like to do?+/-*
read OPERATION
if [ $OPERATION = "+" ]; then
echo Answer
expr $NUM1 + $NUM2
elif [ $OPERATION = "/" ]; then
echo Answer
expr $NUM1 / $NUM2
elif [ $OPERATION = "-" ]; then
echo Answer
expr $NUM1 - $NUM2
elif [ $OPERATION = "*" ]; then
echo Answer
expr $NUM1 * $NUM2
else
echo Please enter one of +/-*
fi
fi
fi
回答by V. Michel
if [[ $OPERATION = "+" ]]; then
echo Answer
expr $NUM1 + $NUM2
elif [[ $OPERATION = "/" ]]; then
echo Answer
expr $NUM1 / $NUM2
elif [[ $OPERATION = "-" ]]; then
echo Answer
expr $NUM1 - $NUM2
elif [[ $OPERATION = "*" ]]; then
echo Answer
expr $NUM1 \* $NUM2
else
echo Please enter one of +/-*
回答by nabeel
first of all according to the error you are getting, all if statements after "read OPERATION" are failing.
首先,根据您得到的错误,“读取操作”之后的所有 if 语句都失败了。
try using [[ ]] instead of [ ] for the if statements
尝试在 if 语句中使用 [[ ]] 而不是 [ ]
plus, its more recommended to wrap the strings with ""
另外,更推荐用“”包裹字符串