shell函数与数组

文章提供了多个Bash脚本示例,包括检查函数参数、判断无位置参数、比较数字、执行算术运算以及使用关联数组统计文件中的信息。例如,函数用于打印状态(OK或FAILED),检查命令行参数的存在,找出两个数字中的最大值,以及在数组中按扩展名统计文件数量。

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

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

#!/bin/bash
function print_status 
{
if [ $# -eq 0 ]; then
    echo -e "\e[31mFAILED\e[0m"
else
    echo -e "\e[32mOK\e[0m"
fi
}
print_status $@

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

#!/bin/bash
location_parameter()
{
if [ $# -eq 0 ];then
echo "错误,无参数输入"
else
echo "有参数输入"
fi
}
location_parameter $@

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

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

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

#!/bin/bash
calculate
{
add=$(( $1 + $2 ))
subtract=$(( $1 - $2 ))
multiply=$(( $1 * $2 ))
if [ $2 -eq 0 ]; then
divide=$(( $2 / $1 ))
else
divide=$(( $1 / $2 ))
fi
}
calculate
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
root_dir="/jiaaoben"  
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、付费专栏及课程。

余额充值