论证过多[if statements]

时间:2015-10-12 21:17:16

标签: bash if-statement

所以我的代码中的所有内容都可以工作,除了乘法(*)

之外
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

继承剧本 它要求你分别输入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

2 个答案:

答案 0 :(得分:2)

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 +/-*

答案 1 :(得分:0)

首先根据你得到的错误,“读取操作”之后的所有if语句都失败了。

尝试使用[[]]而不是[]作为if语句

另外,建议用“”

包装字符串