shell计算器
使用if语句#!/bin/bash# 这是一个计算器read -t 30 -p "Please input the first number: " num1read -t 30 -p "Please input the second number: " num2read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " opif [ -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" ]thenecho "Please input number."exit 1fi# 2.判断操作符是否正确if [ "$op" == "+" ]thenresult=$(($num1 + $num2))elif [ "$op" == "-" ]thenresult=$(($num1 - $num2))elif [ "$op" == "*" ]thenresult=$(($num1 * $num2))elif [ "$op" == "/" ]thenresult=$(($num1 / $num2))elseecho "Please input correct operator, like \"+\", \"-\", \"*\", \"/\"."exit 2fi# 3.打印结果echo "$num1 $op $num2 = $result"exit 0elseecho "Number and oprator must not be empty"exit 3fi
使用case语句
#!/bin/bash# 这是一个计算器read -t 30 -p "Please input the first number: " num1read -t 30 -p "Please input the second number: " num2read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " opif [ -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" ]thenecho "Please input number."exit 1fi# 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 0elseecho "Number and oprator must not be empty"exit 3fi