Multiplication with Expr in Shell Script

Can't use multiplication in arithmetic expression

The problem was as pointed by others the fact than the character * is interpreted by your shell, be it in your terminal or your script. You must use backslash to make the shell understand it is really the character '*'.

Here is a complete solution.
Please, notice the condition [ $# -ne 3 ] rather than [ $# -le 3 ]and the condition [ $OP = '\*' ] rather than else. It is very bad practice to let unasked cases to go through. Doing so may cause hard to debug situations as you have now experienced.

#!/bin/bash

if [ $# -ne 3 ]
then
echo "USAGE : calculate.sh VAR1 OPERATOR VAR2"
exit 1
fi

VAR1=$1
OP=$2
VAR2=$3

if [ $OP = '+' ]
then
echo "$VAR1+$VAR2 = "$(expr $VAR1 + $VAR2)
elif [ $OP = '-' ]
then
echo "$VAR1-$VAR2 = "$(expr $VAR1 - $VAR2)
elif [ $OP = '\*' ]
then
echo "$VAR1*$VAR2 = "$(expr $VAR1 \* $VAR2)
elif [ $OP = '/' ]
then
echo "$VAR1/$VAR2 = "$(expr $VAR1 / $VAR2)
else
echo "Operator must be +-*/"
exit 1
fi
exit 0

Which gives :

adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 '+' 5
6+5 = 11
adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 '-' 5
6-5 = 1
adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 '\*' 5
6*5 = 30
adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 '/' 5
6/5 = 1
adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 '*' 5
./calculate.sh: line 13: [: too many arguments
./calculate.sh: line 17: [: too many arguments
./calculate.sh: line 21: [: too many arguments
./calculate.sh: line 25: [: too many arguments
Operator must be +-*/
adrien@adrienLT:~/Documents/PEV$ ./calculate.sh 6 * 5
USAGE : calculate.sh VAR1 OPERATOR VAR2

Not perfect but much easier to debug.

Multiplication on command line terminal

Yes, you can use bash's built-in Arithmetic Expansion $(( )) to do some simple maths

$ echo "$((5 * 5))"
25

Check the Shell Arithmetic section in the Bash Reference Manual for a complete list of operators.

For sake of completeness, as other pointed out, if you need arbitrary precision, bc or dc would be better.

Shell script to find product of two numbers without using expr and third variable

You must not escape the asterisk inside the arithmetic expression.

echo "product of $a and $b is $((a * b))"

How to multiply two hex numbers in shell script

No need to expr, use $(( )) just like this:

$ echo $((0x10000 * 0x22))
2228224

Or you can use bc like this, indicating input is hex (ibase) and desired output also in hex (obase) (as Adobe's deleted answer states):

$ echo "ibase=16; obase=16; 10000*22" | bc
09 11 05 16 20

$ echo "ibase=16; 10000*22" | bc
2228224


Related Topics



Leave a reply



Submit