Multiplication with expr in a shell script

I am making a basic calculator for adding, subtracting, multiplying and dividing.

The supplement works, but does not multiply. When I try to multiply, I get the answer "You did not start the program correctly":

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

I searched on google where I found the code \\* , but it 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 
+6
source share
2 answers

Your code has a lot of problems. Here is the fix. * means "all files in the current directory". To instead mean an alphabetic asterisk / multiplication symbol, you need to avoid it:

 ./calculator 3 \* 2 

or

 ./calculator 3 "*" 2 

You also need to double the quotation mark "$2" , otherwise * will again begin to mean "all files":

 #!/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 
+10
source

* should get an escape code since it is a special char in shell syntax. (If it is not escaped, it will be expanded to a list of all files in the current directory). But you only need to use one backslash to avoid it:

 ANSWER=`expr $1 \* $3` 
+4
source

Source: https://habr.com/ru/post/978906/


All Articles