Skip to content
Advertisement

Can’t use multiplication in arithmetic expression

#!/bin/bash
if [ $# -lt 3 ] ;then
        echo "USAGE : calculate.sh VAR1 OPERATOR VAR2"
exit 1
fi
VAR1=$1
OP=$2
VAR2=$3
if [ $OP = '+' ];then
        echo "$VAR1+$VAR2=$[$VAR1+$VAR2]"
        exit 0
elif [ $OP = '-' ];then
        echo "$VAR1-$VAR2=$[$VAR1-$VAR2]"
        exit 0
elif [ $OP = '*' ];then
        echo "$VAR1*$VAR2=$[$VAR1*$VAR2]"
        exit 0;
else
        echo "$VAR1/$VAR2=$[$VAR1/$VAR2]"
fi

The above is the content of calculate.sh.

If I use +, -, or /, I get the correct answer, but when I use *, it reports an error:

 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 + 3 
 2+3=5
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 - 3 
 2-3=-1
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 * 3
 ./calculate.sh: line 21: 2/command.sh: syntax error: invalid arithmetic operator (error token is ".sh")
 kdyzm@kdyzm:~/scripts$ ./calculate.sh 2 / 3 
 2/3=0
 kdyzm@kdyzm:~/scripts$

How can I resolve this problem?

Advertisement

Answer

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.

Advertisement