shell基础:使用read、命令行脚本传参实现输入2个整数并计算


shell基础练习题:使用read交互输入,命令行脚本传参2种方式,实现输入2个整数数字,并计算加减乘除。考察shell基础知识包括:变量定义、read、if判断语句、正则表达式等知识;
 
第一种方式:read交互输入参数
 
思路为:判断输入的第2个变量是否为空,为空则提示输入2个数字;不为空则判断输入的是否为整数,用到expr,作用为让2个变量进行相加,如果结果为0说明输入2个为数字,如结果非0则说明输入非整数,提示输入的不是非整数;
#!/bin/bash
read -p "pls input two number:" a b
if  [ ! -z $b ]
then
     expr $a + $b &>/dev/null
     if [ $? -eq 0 ]
      then
          echo "a-b=$(($a-$b))"
          echo "a+b=$(($a+$b))"
          echo "a*b=$(($a*$b))"
          echo "a/b=$(($a/$b))"
         else
              echo "input is not zhengshu"
         fi
else
     echo "you must input two number"
fi

 

执行结果如下:输入字母会报错,输入不是整数;只输入1个参数也会报错;
 
[baby@localhost ~]$ sh a.sh
pls input two number:4 2
a-b=2
a+b=6
a*b=8
a/b=2
[baby@localhost ~]$ sh a.sh
pls input two number:a 2
input is not zhengshu
[baby@localhost ~]$ sh a.sh
pls input two number:10
you must input two number

 

脚本有bug,如果输入3个参数的话会报错如下:
[baby@localhost ~]$ sh a.sh
pls input two number:1 3 3
a.sh: line 3: [: 3: binary operator expected
you must input two number
 
针对上面的脚本bug修改如下:
 
思路为:多添加一个变量c,并多了if判断,先判断$a是否为空,如为空提示输入2个数字并退出;然后判断$b是否为空,如未空提示输入2个数字并退出;只有$a $b都不为空即都有输入值,再判断$c是否为空,如未空执行下面的整数判断,如$c不为空同样提示输入2个数字并退出;
 
#!/bin/bash
read -p "pls input two number:" a b c
if [ -z $a ]
  then
 echo "you must input two number"
 exit
elif [ -z $b ]
  then
 echo "you must input two number"
 exit
fi
if [ -z $c ]
then
 expr $a + $b &>/dev/null
 if [ $? -eq 0 ]
  then
  echo "a-b=$(($a-$b))"
  echo "a+b=$(($a+$b))"
  echo "a*b=$(($a*$b))"
  echo "a/b=$(($a/$b))"
 else 
  echo "input is not zhengshu"
 fi
else
 echo "you must input two number"
fi

 

执行结果如下,什么都不输入,输入一个字符都会提示必须输入2个数字;输入2个值中有字母提示输入的非整数;
 
[baby@localhost ~]$ sh a.sh  
pls input two number:
you must input two number
[baby@localhost ~]$ sh a.sh
pls input two number:1
you must input two number
[baby@localhost ~]$ sh a.sh
pls input two number:1 a
input is not zhengshu
[baby@localhost ~]$ sh a.sh
pls input two number:2 1
a-b=1
a+b=3
a*b=2
a/b=2

 

 
第二种方式:命令行脚本传参方式
 
思路为:定义a b两个变量,接受命令行传递的参数;$#为输入参数的总个数;判断输入的参数个数不等于2,则提示必须输入2个数字;等于2的话执行下面的脚本;
 
[baby@localhost ~]$ cat b.sh
#!/bin/bash
a=$1
b=$2
if [ $# -ne 2 ]
then
 echo "you must input two number"
 exit 1
else
 expr $a + $b &>/dev/null
 if [ $? -eq 0 ]
  then
  echo "a-b=$(($a-$b))"
  echo "a+b=$(($a+$b))"
  echo "a*b=$(($a*$b))"
  echo "a/b=$(($a/$b))"
 else
  echo "input is not zhengshu"
  exit 1
 fi
fi

 

执行结果如下:传参为空,参数为3个都会提示必须输入2个数字;传参包含非数字则提示输入的不是整数;
 
[baby@localhost ~]$ sh b.sh 3 a
input is not zhengshu
[baby@localhost ~]$ sh b.sh 3 2 3
you must input two number
[baby@localhost ~]$ sh b.sh 3 2
a-b=1
a+b=5
a*b=6
a/b=1

 

 
总结:
 
read可以和用户交互性较好,脚本较为复杂多了if判断效率不高;
 
命令行传参使用表达式判断输入参数,执行效率和理解性较好;

相关内容