0

I must write the code support 5 calculations (+, -, , /, %) in Bash Script. It get an input form: and return the result. But when i try multiply calculation (), it not return result

This is my code:

#!/bin/bash

read -p ">>" INPUT
operand1=$(echo $INPUT | cut -d' ' -f 1)
operator=$(echo $INPUT | cut -d' ' -f 2)
operand2=$(echo $INPUT | cut -d' ' -f 3)
case $operator in
    "+") res=$((operand1 + $operand2));;
    "-") res=$((operand1 - $operand2));;
    "*") res=$((operand1 \* $operand2));;
    "/") if [[ $operand2 -eq 0 ]]; then
            echo "MATH ERROR"
            continue
         else
            res=`echo "scale=2; $operand1 / $operand2" | bc`
         fi;;
    "%") res=`echo $operand1 % $operand2 | bc`;;
    esac
echo "$res"

I also these way but it still not work

"*") res=$((operand1 * operand2));;

and

"*") res=`echo $operand1 \* $operand2 | bc`;;

What wrong here with my code in multiply calculation?? Please help me

daniel12
  • 33
  • 4

1 Answers1

1

I think you are encountering file system globbing in bash where '*' is magic and matches files in the current directory.

This can be disabled by adding:

set -f

To your script before your code block.

For more information on set see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html

And there are various other strategies discussed here: Stop shell wildcard character expansion?

With this, you will not need to backslash '*' in your computation and go with:

    "*") res=$((operand1 * $operand2));;
Bret Weinraub
  • 1,943
  • 15
  • 21