21. 脚本:算术运算

2.数值计算脚本

vim calculate.sh
#!/bin/bash
#说明:运行脚本,输入数1,输入运算符,输入数2,得到结果

#1.提示函数
print_usage(){
    printf "please enter an integer\n"
    exit 1
}

#2.接收值1
read -p "please input your number:" firstnum

#3.判断输入的是否是纯数字
if [ -n `echo $firstnum|sed 's/[0-9]//g'` ];then
    print_usage
fi

#4.接收运算符
read -p "please input an operator:" operator

#5.对运算符判断,只能输入加减乘除
if [  "${operator}" != "+"  ] &&  [  "${operator}" != "-"  ] &&  [  "${operator}" != "*"  ] &&  [  "${operator}" != "/"  ];then
    echo "only can input  +|-|*|/"
    exit 2
fi

#6.接收值2,并判断
read -p "please input second number:" secondnum
if [ -n `echo $secondnum|sed 's/[0-9]//g'` ];then
    print_usage
fi

#7.计算
echo "${firstnum}${operator}${secondnum}=$((${firstnum}${operator}${secondnum}))"

最后更新: 2022-02-19 13:59:07