【问题标题】:Problems to use "Mul" and "Mod" operators in Bash在 Bash 中使用“Mul”和“Mod”运算符的问题
【发布时间】:2012-01-10 12:32:50
【问题描述】:

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

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:非法字符:~

【问题讨论】:

    标签: bash math module multiplication arithmetic-expressions


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 好的,谢谢。我也找到了这个解决方案: mul=$(echo "$a * $b" | bc -l) 也适用于%
      猜你喜欢
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2014-10-31
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多