1
#!/bin/sh

echo "Welcome to our calculator"

echo "Please insert your two numbers"

echo "Number 1:"

read number1

echo "Number 2:"

read number2

echo "Please type (+,-,/,*) if you want to add or substract or 
multiply or divide respectively: "
read operand

if [ $operand = '+' ]; then

        echo `expr $number1 + $number2`


elif [ $operand = '-' ]; then

        echo `expr $number1 - $number2`

elif [ $operand = '/' ]; then

        echo `expr $number1 / $number2`

elif [ $operand = '*' ] ;then

        echo `expr $number1 * $number2`

else

        echo "Invalid Input"

fi

exit 0

How can I fix this but still be able to keep if statement because I have to use if statement specifically for this assignment, so I can't use loop or anything else. Thank you in advance.

pmdj
  • 22,018
  • 3
  • 52
  • 103
anna
  • 11
  • 3
  • Simplest fix for all your problems with the use of an asterisk in your script is to add a line containing `set -f`` immediately after the shebang. This disables pathname expansion. – fpmurphy May 28 '22 at 15:23
  • 2
    pmdj is on the right track. Quote all your variables and any special characters. Also consider using `case` instead of `if`, and built in arithmetic instead of `expr`. – dan May 28 '22 at 16:12
  • [shellcheck.net](https://www.shellcheck.net) will point out a number of problems here; I strongly recommend using it to sanity-check your scripts. In this case, the main problems are not double-quoting variable references (see ["When should I wrap quotes around a shell variable?"](https://stackoverflow.com/questions/10067266) -- short answer: almost always). Also, using ```echo `eval ...` ``` is unnecessarily complicated, you should either just use `eval ...` directly (no `echo` or backticks), or use `echo $(( ... ))` (more modern expression syntax). – Gordon Davisson May 28 '22 at 17:02

1 Answers1

1

The asterisk (*) token has a special meaning in bash, and on its own, it expands to the list of all non-hidden files in the current directory. In your case, this expansion gets passed to the expr command, which can't make any sense of it. To pass a literal asterisk to the command, you'll need to escape it using the backslash (\) character, like so:

echo `expr $number1 \* $number2`

For future debugging, try replacing expr with echo to see exactly what arguments get passed to the command.

pmdj
  • 22,018
  • 3
  • 52
  • 103
  • 1
    This is true, but in this case it's actually unquoted `$operand` in the preceding test which is causing glob expansion and the error (`expr` isn't executed because the test fails). OP must quote both: `[ "$operand" = \* ]` and `expr "$number1" \* "$number2"`. – dan May 28 '22 at 16:10