【shell一天一练】函数

93 阅读1分钟

今日小练题目📢

使用传参的方法写个脚本,实现加减乘除的功能。

例如: sh a.sh 1 2,这样会分别计算加、减、乘、除的结果。

要求:

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

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

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

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

优秀作业🤌🏻

#!/bin/bash
#author:xYLiuuuuuu
#date:2024-12-03

if [ $# -ne 2 ]
then
        echo "The number of parameter is not 2, Please useage: ./$0 1 2"
        exit 1
fi

is_int()
{
        if echo "$1"|grep -q '[^0-9]'
        then
                echo "$1 is not integer number."
                exit 1
        fi
}

max()
{
        if [ $1 -ge $2 ]
        then
                echo $1
        else
                echo $2
        fi
}

min()
{
        if [ $1 -lt $2 ]
        then
                echo $1
        else
                echo $2
        fi
}

sum()
{
        echo "$1 + $2 = $[$1+$2]"
}

minus()
{
        big=`max $1 $2`
        small=`min $1 $2`
        echo "$big - $small = $[$big-$small]"
}

mult()
{
        echo "$1 * $2 = $[$1*$2]"
}

div()
{
        big=`max $1 $2`
        small=`min $1 $2`
        d=`echo "scale = 2; $big / $small"|bc`
        echo "$big / $small = $d"
}

is_int $1
is_int $2
sum $1 $2
minus $1 $2
mult $1 $2
div $1 $2

敲黑板📝

  • grep -q参数用于if语句判断很好使
$ cat a.txt
nihao 
nihaooo
hello

$ if  grep -q hello a.txt ; then echo yes;else echo no; fi 
yes

$ if grep -q word a.txt; then echo yes; else echo no; fi
no
  • 数学运算可以借助bc,bc为Linux命令行里的一个计算器