Unix脚本-部门



我正在bash shell中构建一个计算器,但我在除法方面遇到了问题。我试着在整行周围加括号$((((,然后只在两个操作数周围加括号,但总数仍然不正确。我做错了什么?

#!/bin/bash
# Read user input
echo "Enter operand:"
read num1
echo "Enter operator:"
read operator
echo "Enter operand:"
read num2
case $operator in
+) total=`echo $num1 + $num2 | bc`;;
-) total=`echo $num1 - $num2 | bc`;;
*) total=`echo $num1 * $num2 | bc`;;
/) total=`echo scale=2; $(( $num1 / $num2 )) | bc`;;
esac
echo "Result: $num1 $operator $num2 = $total"

您需要在echo中引用文本并删除$((((。

echo "scale=2; $num1 / $num2" | bc

在您的代码中,您希望将结果分配给total,因此您仍然需要在子shell 中运行整个echo命令字符串

total=$(echo "scale=2; $num1 / $num2" | bc)

或者同样的事情,但使用反勾

total=`echo "scale=2; $num1 / $num2" | bc`

最新更新