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