版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
shell计算器
- 使用if语句
#!/bin/bash
# 这是一个计算器
read -t 30 -p "Please input the first number: " num1
read -t 30 -p "Please input the second number: " num2
read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " op
if [ -n "$num1" -a -n "$num2" -a -n "$op" ]
then
# 1.校验两个操作数必须为数值
test1=$(echo $num1 | sed 's/[0-9]//g')
test2=$(echo $num2 | sed 's/[0-9]//g')
if [ -n "$test1" -o -n "$test2" ]
then
echo "Please input number."
exit 1
fi
# 2.判断操作符是否正确
if [ "$op" == "+" ]
then
result=$(($num1 + $num2))
elif [ "$op" == "-" ]
then
result=$(($num1 - $num2))
elif [ "$op" == "*" ]
then
result=$(($num1 * $num2))
elif [ "$op" == "/" ]
then
result=$(($num1 / $num2))
else
echo "Please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
exit 2
fi
# 3.打印结果
echo "$num1 $op $num2 = $result"
exit 0
else
echo "Number and oprator must not be empty"
exit 3
fi
- 使用case语句
#!/bin/bash
# 这是一个计算器
read -t 30 -p "Please input the first number: " num1
read -t 30 -p "Please input the second number: " num2
read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " op
if [ -n "$num1" -a -n "$num2" -a -n "$op" ]
then
# 1.校验两个操作数必须为数值
test1=$(echo $num1 | sed 's/[0-9]//g')
test2=$(echo $num2 | sed 's/[0-9]//g')
if [ -n "$test1" -o -n "$test2" ]
then
echo "Please input number."
exit 1
fi
# 2.判断操作符是否正确
case $op in
"+")
result=$(($num1 + $num2))
;;
"-")
result=$(($num1 - $num2))
;;
"*")
result=$(($num1 * $num2))
;;
"/")
result=$(($num1 / $num2))
;;
*)
echo "Please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
exit 2
;;
esac
# 3.打印结果
echo "$num1 $op $num2 = $result"
exit 0
else
echo "Number and oprator must not be empty"
exit 3
fi