shell习题-脚本传参(运算)

1.要求:
使用传参的方法写个脚本,实现加减乘除的功能。
例如:  sh  a.sh  1   2,
这样会分别计算加、减、乘、除的结果。

1 脚本需判断提供的两个数字必须为整数


2 当做减法或者除法时,需要判断哪个数字大


3 减法时需要用大的数字减小的数字


4 除法时需要用大的数字除以小的数字,并且结果需要保留两个小数点

2.脚本答案:


[root@liang 2018-06-22]# cat operation.sh 
#!/bin/bash
if [ $# -ne 2 ];then
        echo "Error:Please enter two Numbers!"
        exit 1
fi
Num1=`echo $1|sed 's/[0-9]//g'`
Num2=`echo $2|sed 's/[0-9]//g'`
Null=
if [ "$Num1" != "$Null" ];then
        echo "Errpr:Please enter an integer $1 "
        exit 2 
fi 


if [  "$Num2" != "$Null" ];then
        echo "Errpr:Please enter an integer $2 "
        exit 3
fi
#jiafa
((add=$1+$2))
echo "${1} + ${2} = ${add}"
#chengfa
((take=$1*$2))
echo "${1} * ${2} = ${take}"
if [ $1 -gt $2 ];then
        #jianfa
        ((subtract=$1-$2))
        echo "${1} - ${2} = ${subtract}"
        #chufa
        divide=`echo "scale=2; ${1}/${2}" | bc`
        echo "${1} / ${2} = ${divide}"
else
                #jianfa
        ((subtract=$2-$1))
        echo "${2} - ${1} = ${subtract}"
        #chufa
        divide=`echo "scale=2; ${2}/${1}" | bc`
        echo "${2} / ${1} = ${divide}"
fi

3.测试:

[root@liang 2018-06-22]# bash operation.sh 1 1 1
Error:Please enter two Numbers!
[root@liang 2018-06-22]# bash operation.sh a 1
Error:Please enter an integer a 
[root@liang 2018-06-22]# bash operation.sh 1 b
Error:Please enter an integer b 
[root@liang 2018-06-22]# bash operation.sh 5 11
5 + 11 = 16
5 * 11 = 55
11 - 5 = 6
11 / 5 = 2.20
[root@liang 2018-06-22]# bash operation.sh 11 5
11 + 5 = 16
11 * 5 = 55
11 - 5 = 6
11 / 5 = 2.20

猜你喜欢

转载自blog.csdn.net/liang_operations/article/details/80771545