【RHCE】Shell脚本3——函数与数组(练习)

1、编写函数,实现打印绿色 OK 和红色 FAILED;判断是否有参数,存在为OK,不存在为FAILED。

脚本文件:

 

2、编写函数,实现判断是否无位置参数,如无参数,提示错误。

脚本文件:

#!/bin/bash

func() {
        if [ -z "$1" ]
        then
                echo "错误"
        fi
}

func $1

 

3、编写函数实现两个数字做为参数,返回最大值

脚本文件:

#!/bin/bash

max() {
        read -p "first num: " num1
        read -p "second num: " num2
        if [ $num1 -ge $num2 ]
        then
                echo "$num1"
        else
                echo "$num2"
        fi
}

max

 

4、编写函数,实现两个整数位参数,计算加减乘除。

脚本文件:

#!/bin/bash

read -p "first num: " num1
read -p "second num: " num2

calculate() {
        num1=$1
        num2=$2

        # 提取整数部分
        int1=${num1%.*}
        int2=${num2%.*}

        add=$(( int1+int2 ))
        sub=$(( int1-int2 ))
        mul=$(( int1*int2 ))

        # ne ===> 判断两个数是否不相等
        if [ $int2 -ne 0 ];
        then
                div=$(( int1/int2 ))
        else
                div="除数为0,除法运算不成立!!!"
        fi

        echo "加法:$add"
        echo "减法:$sub"
        echo "乘法:$mul"
        echo "除法:$div"
}

calculate $num1 $num2

5、将/etc/shadow文件的每一行作为元数赋值给数组

脚本文件:

#!/bin/bash

i=0
declare -A array
for line in `cat /etc/shadow`
do
        array[$i]=$line
        i=`expr $i + 1`
done

echo ${array[*]}

6、使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量

脚本文件:

#!/bin/bash

i=0
declare -A array
for line in `cat /etc/passwd | cut -d : -f 7 | sort -s | uniq -c |sort -n`
do
array[$i]=$line
i=`expr $i + 1`
done

echo ${array[*]}

7、使用关联数组按扩展名统计指定目录中文件的数量

#!/bin/bash

i=0
declare -A array
for line in `cat /etc/passwd | cut -d : -f 2,3 | sort -s | uniq -c`
do
array[$i]=$line
i=`expr $i + 1`
done

echo ${array[*]}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值