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

本文介绍了一个Shell脚本,该脚本通过传参方式实现了基本的加、减、乘、除运算功能。当执行减法或除法时,脚本会自动判断并使用较大数值作为被减数或被除数,同时除法结果保留两位小数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值