标签:null
1.read读取方式: [root@www scripts]# vim read_1.sh 1 #!/bin/bash 2 # Filename: read_1.sh 3 # Describe: Integer arithmetic 4 # Author: Lijun 5 # Date: 2015-08-24 6 # Version: 1.0.1 7 8 read -p "Please input two nums: " a b 9 10 if [ -z $a ] || [ -z $b ] 11 then 12 echo "Please input two nums again." 13 exit 1 14 fi 15 16 expr $a + 1 > /dev/null 2>&1 17 RETVAL1=$? 18 expr $b + 1 > /dev/null 2>&1 19 RETVAL2=$? 20 21 if [ $RETVAL1 -ne 0 ] || [ $RETVAL2 -ne 0 ] 22 then 23 echo "Please input two nums(must be integer)." 24 exit 2 25 else 26 echo "a+b=$(( $a + $b ))" 27 echo "a-b=$(( $a - $b ))" 28 echo "a*b=$(( $a * $b ))" 29 echo "a/b=$(( $a / $b ))" 30 echo "a%b=$(( $a % $b ))" 31 exit 0 32 fi
2.脚本传参的方式:
[root@www scripts]# vim read_2.sh 1 #!/bin/bash 2 # Filename: read_2.sh 3 # Describe: Integer arithmetic 4 # Author: Lijun 5 # Date: 2015-08-24 6 # Version: 1.0.2 7 8 a=$1 9 b=$2 10 11 if [ $# -ne 2 ] 12 then 13 echo "Usage: sh `basename $0` {NUM1 NUM2}" 14 exit 1 15 fi 16 17 expr $a + 1 > /dev/null 2>&1 18 RETVAL1=$? 19 expr $b + 1 > /dev/null 2>&1 20 RETVAL2=$? 21 22 if [ $RETVAL1 -ne 0 ] || [ $RETVAL2 -ne 0 ] 23 then 24 echo "Please input two integers(must be integer)." 25 exit 2 26 else 27 echo "a+b=$(( $a + $b ))" 28 echo "a-b=$(( $a - $b ))" 29 echo "a*b=$(( $a * $b ))" 30 echo "a/b=$(( $a / $b ))" 31 echo "a%b=$(( $a % $b ))" 32 exit 0 33 fi
3. 整数判断的另一种方法: [root@www scripts]# vim read_3.sh 1 #!/bin/bash 2 # Filename: read_1.sh 3 # Describe: Integer arithmetic 4 # Author: Lijun 5 # Date: 2015-08-24 6 # Version: 1.0.1 7 8 read -p "Please input two nums: " a b 9 10 if [ -z $a ] || [ -z $b ] 11 then 12 echo "Please input two nums again." 13 exit 1 14 fi 15 16 echo $a |egrep -o "[^0-9]{1,}" > /dev/null || echo $b |egrep -o "[^0-9]{1,}" > /dev/null && 17 echo "Please input two nums(must be integer)."|| { 18 echo "a+b=$(( $a + $b ))" 19 echo "a-b=$(( $a - $b ))" 20 echo "a*b=$(( $a * $b ))" 21 echo "a/b=$(( $a / $b ))" 22 echo "a%b=$(( $a % $b ))" 23 }
shell编程实例---实现整数的加减乘除余运算(利用read和脚本传参的方式)
标签:null
原文地址:http://l19891223j.blog.51cto.com/888280/1687989