14

I am making a basic calculator to add, subtract, multiply, and divide.

Addition works, but not multiplication. When I attempt to multiply, I get the "You did not run the program correctly" response:

$ ./calculator 4 + 5
9
$ ./calculator 4 * 5
You did not run the program correctly
Example: calculator 4 + 5

I've searched around on google, where I found the \\* code, but still doesn't work. Can someone provide me with a solution or explanation?

Here is my code

#!/bin/bash

if [ $# != 3 ]; then  
  echo You did not run the program correctly   
  echo Example: calculator 4 + 5                
  exit 1 
fi

if [ $2 = "+" ]; then    
  ANSWER=`expr $1 + $3`    
 echo $ANSWER 
fi

if [ $2 = "*" ]; then
  ANSWER=`expr $1 \\* $3`  
  echo $ANSWER 
fi

exit 0
that other guy
  • 116,971
  • 11
  • 170
  • 194
Alex Wolfe
  • 141
  • 1
  • 1
  • 3
  • It's unlikely you need `expr`; `ANSWER=$(( $1 + $3 ))`, for example, should work with any shell you are likely to be using with Linux. – chepner Nov 30 '14 at 21:36

3 Answers3

28

Your code has many problems. Here is a fix. * means "all files in the current directory". To instead mean a literal asterisk/multiplication character, you have to escape it:

./calculator 3 \* 2

or

./calculator 3 "*" 2

You also have to double quote "$2", otherwise * will start meaning "all files" again:

#!/bin/bash
#Calculator
#if [ `id -u` != 0 ]; then
#  echo "Only root may run this program." ; exit 1
#fi
if [ $# != 3 ]; then   
  echo "You did not run the program correctly"
  echo "Example:  calculator 4 + 5"
  exit 1
fi
# Now do the math (note quotes)
if [ "$2" = "+" ]; then echo `expr $1 + $3`
elif [ "$2" = "-" ]; then echo `expr $1 - $3`
elif [ "$2" = "*" ]; then echo `expr $1 \* $3`
elif [ "$2" = "/" ]; then echo `expr $1 / $3`
fi
exit 0
that other guy
  • 116,971
  • 11
  • 170
  • 194
hongo
  • 687
  • 1
  • 6
  • 10
15

The * needs to get escaped since it is a special char in shell syntax. (If not escaped, it will get expanded to the list of all files in the current directory). But you need to use just a single backslash in order to escape it:

ANSWER=`expr $1 \* $3` 
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

For two elements:

#!/bin/bash
echo "Enter two numbers:"
read a
read b
mult=`expr $a \* $b`
echo "Multipication:" $mult

For array:

#!/bin/bash
echo "Enter total numbers:"
read n
mult=1
echo "Enter Numbers:"
for (( i = 0; i < n; i++ ))
do
read a[i]
mult=`expr $mult \* ${a[$i]}`
done
echo "Original numbers:" ${a[@]}
echo "Multipication:" $mult
tdy
  • 36,675
  • 19
  • 86
  • 83
Ravikant
  • 11
  • 3