2

So everything in my code works, all but the multiplication 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

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
codeforester
  • 39,467
  • 16
  • 112
  • 140
Kyler
  • 39
  • 1
  • 1
  • 5

2 Answers2

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 +/-*
V. Michel
  • 1,599
  • 12
  • 14
  • Either that, or put double-quotes around `$OPERATION`, *or both*. In a shell script, if you ever see a variable reference without double-quotes around it, a little alarm should go off in your head that there's probably something wrong. – Gordon Davisson Oct 13 '15 at 04:36
  • What you put up works great thanks!, and ill put double quotes around variable references from now on. Is the [[ ]], the way your supposed to do it? – Kyler Oct 13 '15 at 08:45
  • Yes Kyler, [[ expression ]] return a status of 0 or 1 depending on the evaluation of the conditional expression expression (man bash) and expr need \* or \'*\' just try expr 2 \* 3, expr 2 '*' 3 and expr 2 *3 -> syntax error. – V. Michel Oct 13 '15 at 17:34
1

first of all according to the error you are getting, all if statements after "read OPERATION" are failing.

try using [[ ]] instead of [ ] for the if statements

plus, its more recommended to wrap the strings with ""

nabeel
  • 319
  • 1
  • 9