0

我不明白为什么在这段代码中

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

正确执行 SUM、SUB 和 DIV,但如果我想做 MUL 或 MOD 操作,它会给我一个错误:

(standard_in) 1: 语法错误

(standard_in) 1:非法字符:~

(standard_in) 1:非法字符:~

4

2 回答 2

1

这应该可以按您的预期工作。你需要逃避*%。你有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
于 2011-12-01T11:02:36.580 回答
1

您需要引用*,否则它会被 shell 扩展。

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

%应该可以不加引号,但为简单起见,您可以引用所有运算符。

于 2011-12-01T11:02:55.773 回答