Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutilply calculation in Bash Script

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

and

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

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

>Solution :

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));;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading