algazi algazi - 4 months ago 22
Bash Question

error calc bash script

#!/bin/bash


if [ $2 == "+" ]; then
echo $1 + $3 | bc
elif [ $2 == "-" ]; then
echo $1 -$3 | bc
elif [ $2 == "/" ]; then
echo $1 / $3 | bc -l
elif [ ${2: -0} == "\*" ]; then
echo $1 \* $3 | bc
fi





[ali@localhost Desktop]$ ./q1.sh 5 \* 2
./q1.sh: line 4: [: too many arguments
./q1.sh: line 6: [: too many arguments
./q1.sh: line 8: [: too many arguments
./q1.sh: line 10: [: too many arguments

Answer

Below script would do :

   #!/bin/bash
    if [ "$2" = "+" ] # == won't work with old test ie [],
    #use [[ ]]  if you wish to use ==
    then
     echo "$1 + $3" | bc
    elif [ "$2" = "-" ]; then
     echo "$1 - $3" | bc
    elif [ "$2" = "/" ]; then
      if [ "$3" -ne 0 ]
      then
        echo "scale=3;$1 / $3" | bc -l # scale gives the precision of the results
      else
        echo "Division by zero not possible"
      fi
    elif [ "$2" = '*' ]; then
       # You need to escape or quote the asterisk in the command line
       # when calling the script like ./script 3 \* 4
       echo "$1 * $3" | bc
    fi 2>/dev/null # For suppressing the errors when using '\*' as $2

Sample Run

$ ./38464438.sh 4 + 5
9
$ ./38464438.sh 4 - 5
-1
$ ./38464438.sh 4 / 5
.800
$ ./38464438.sh 4 \* 5
20