shell脚本函数与数组的简单练习

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

#!/bin/bash
#########################
#File name:14.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-05-06 17:36:22
#Description:
#########################
colour() {
    if [ $# -eq 0 ];then
        echo -e "\e[31mFAILED\e[0m"
    else
        echo -e "\e[32mOK\e[0m"
fi
    return
}
colour $@

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

#!/bin/bash
#########################
#File name:15.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-05-06 17:54:17
#Description:
#########################
Position() {

    if [ $# -eq 0 ];then
        echo "错误请输入参数"
    fi
}
Position $@

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

#!/bin/bash
number(){
if [ $1 -gt $2 ];then
    echo $1
    else
    echo $2
fi
}
max=$(number $1 $2)
echo "最大值为:$max"

 

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

#!/bin/bash
count()
{
add=$(( $1 + $2 ))
subtract=$(( $1 - $2 ))
multiply=$(( $1 * $2 ))
if [ $2 -eq 0 ]; then
divide=$(( $2 / $1 ))
else
divide=$(( $1 / $2 ))
fi
}
count $@
echo "加减乘除分别是:$add $subtract $multiply $divide"

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

#!/bin/bash
readarray -t shadow_array < "/etc/shadow"
for line in "${shadow_array[@]}"
do
    echo "$line"
done

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

#!/bin/bash
declare -A shell_count
while read line
do
  user=$(echo $line | cut -d':' -f1)
  shell=$(echo $line | cut -d':' -f7)
  if [[ ${shell_count[$shell]} ]]; then
    shell_count[$shell]=$(( ${shell_count[$shell]} + 1 ))
  else
    shell_count[$shell]=1
  fi
done < /etc/passwd
for shell in "${!shell_count[@]}"
do
  count=${shell_count[$shell]}
  echo "Shell $shell: $count user(s)"
done

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

#!/bin/bash
#########################
#File name:20.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-05-12 21:23:48
#Description:
#########################



root_dir="/root"
find "$root_dir" -type f -printf '%f\n' | \
    awk -F . '{count[$NF]++} END {for (ext in count) print "扩展名: " ext ", 文件数量: " count[ext]}'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值