0

I don't understand why in this code

echo "Please, give me two numbers:"
echo 1: 
read a
echo 2:
read b 
echo "a = $a"
echo "b = $b"

OPT="Sum Sub Div Mul Mod"
 select opt in $OPT; do

if [ $opt = "Sum"  ]; then
 sum=$(echo $a + $b | bc -l)
 echo "SUM is: $sum"

elif [ $opt = "Sub"  ]; then
 sub=$(echo $a - $b | bc -l)
 echo "SUB is: $sub"

elif [ $opt = "Div"  ]; then
  div=$(echo $a / $b | bc -l)
  echo "DIV is: $div"

elif [ $opt = "Mul"  ]; then
  mul=$(echo $a * $b | bc -l)
  echo "MUL is: $mul"

elif [ $opt = "Mod"  ]; then
  mod=$(echo $a % $b | bc -l )
  echo "MOD is: $mod"

else
 clear
 echo "wrong choise"
 exit

fi

done

execute correctly SUM, SUB and DIV, but if I want to do the MUL or MOD operation, it gives me an error:

(standard_in) 1: syntax error

(standard_in) 1: illegal character: ~

(standard_in) 1: illegal character: ~

2 Answers 2

1

This should work as you expect. You need to escape the * and the %. And you had echo "MOD is $mul":

echo "Please, give me two numbers:"
echo 1: 
read a
echo 2:
read b 
echo "a = $a"
echo "b = $b"

OPT="Sum Sub Div Mul Mod"
 select opt in $OPT; do

if [ $opt = "Sum"  ]; then
 sum=$(echo $a + $b | bc -l)
 echo "SUM is: $sum"

elif [ $opt = "Sub"  ]; then
 sub=$(echo $a - $b | bc -l)
 echo "SUB is: $sub"

elif [ $opt = "Div"  ]; then
  div=$(echo $a / $b | bc -l)
  echo "DIV is: $div"

elif [ $opt = "Mul"  ]; then
  mul=$(echo $a \* $b | bc -l)
  echo "MUL is: $mul"

elif [ $opt = "Mod"  ]; then
  mod=$(echo $a \% $b | bc -l )
  echo "MOD is: $mod"

else
 clear
 echo "wrong choice"
 exit

fi

done
Sign up to request clarification or add additional context in comments.

Comments

1

You need to quote the *, otherwise it's expanded by the shell.

    mul=$(echo $a '*' $b | bc -l)

% should be fine unquoted, but for simplicity you can quote all the operators.

1 Comment

Yes thanks. I also find this solution: mul=$(echo "$a * $b" | bc -l) and also for %.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.