思路:函数先计算数值加减乘除,case赋值输出对应的加减乘除
#!/bin/bash
add() {
add=$[$1+$2]
echo "outcome:$1+$2=$add"
}
minus() {
min=$[$1-$2]
echo "outcome:$1-$2=$min"
}
multiply() {
mult=$[$1*$2]
echo "outcome:$1x$2=$mult"
}
divide() {
div=$[$1/$2]
echo "outcome:$1/$2=$div"
}
positive_integer() {
if echo $1| grep -q [^0-9];then
echo "please input a positive number."
exit 2
fi
}
if [ $# -ne 3 ];then #判断输入参数为3
#第二个参数不能为*,shell脚本中*代表是特殊字符,因此乘应使用x代替
echo "please input three parameter,format like: number1 (+ - x /) number2"
exit 1
else
positive_integer $1#调用函数判断正整数
positive_integer $3#调用函数判断正整数
fi
case $2 in
x)
multiply $1 $3
;;
+)
add $1 $3
;;
-)
minus $1 $3
;;
/)
if [ $1 -lt $3 ];then
echo "input first number $1 must great second number $3,else outcome number is zero."
else
divide $1 $3
fi
;;
\*)
echo "please input three parameter,format like: number1 (+ - x /) number2"
;;
esac
用法 : sh jjcc.sh 3 x 4
输出:outcome:3 x 4=12
注:除法如果想保留两位小数可以使用 echo "scale=2;1/2"| bc实现
来源:51CTO
作者:Margotchen
链接:https://blog.51cto.com/11594671/2550835