005#验证整数输入
验证整数输入,注意整数包含正负整数。
1 #!/usr/bin/env bash 2 3 validint(){ 4 number=$1 5 min=$2 6 max=$3 7 8 # 空值检测 9 if [ -z $number ]; then 10 echo "You didn't input anything." >&2 11 return 1 12 fi 13 14 # 负数符号检测 15 if [ "${number%${number#?}}" = "-" ]; then 16 num="${number#?}" 17 else 18 num="${number}" 19 fi 20 21 # 检查除负数符号后的数字是否是整数 22 nodigits=$(echo $num | sed 's/[[:digit:]]//g') 23 if [ ! -z "$nodigits" ]; then 24 echo "Invalid number format. Only digits, no commas, spaces, etc." >&2 25 return 1 26 fi 27 28 # 判断输入值是否小于指定最小值 29 if [ ! -z $min ]; then 30 if [ $number -lt $min ]; then 31 echo "You value is too small. the smallest value is $min" >&2 32 return 1 33 fi 34 fi 35 36 # 判断输入值是否大于指定最大值 37 if [ ! -z $max ]; then 38 if [ $number -gt $max ]; then 39 echo "You value is too big. the largest value is $max" >&2 40 return 1 41 fi 42 fi 43 44 return 0 45 } 46 47 # 验证输入 48 if validint $1 $2 $3; then 49 echo "Input is valid integer within your constraints." 50 fi
*** 你必须十分努力,才能看起来毫不费力 ***