计算:判断如果不是数字,则不继续运行方法
read 读入和整数判断方法
#!/bin/bash while true;do read -p "Num1 Num2:" num1 num2 expr $num1 + 0 &>/dev/null [ $? -ne 0 ]&& continue expr $num2 + 0 &>/dev/null [ $? -ne 0 ]&& continue || break #break如果是整数,则结束这个循环; done echo "num1-num2 =$(( $num1 - $num2 ))" echo "num1+num2 =$(( $num1 + $num2 ))" echo "num1*num2 =$(( $num1 * $num2 ))" echo "num1/num2 =$(( $num1 / $num2 ))" echo "num1**num2 =$(( $num1 ** $num2 ))" echo "num1%num2 =$(( $num1 % $num2 ))"
增加对传入参数的判断:
#!/bin/bash num1="$1" num2="$2" if [ $# -ne 2 ];then echo "arge error." exit 1 fi expr $num1 + 0 &>/dev/null [ $? -ne 0 ]&& exit expr $num2 + 0 &>/dev/null [ $? -ne 0 ]&& exit echo "num1-num2 =$(( $num1 - $num2 ))" echo "num1+num2 =$(( $num1 + $num2 ))" echo "num1*num2 =$(( $num1 * $num2 ))" echo "num1/num2 =$(( $num1 / $num2 ))" echo "num1**num2 =$(( $num1 ** $num2 ))" echo "num1%num2 =$(( $num1 % $num2 ))"