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]}'