1、编写函数,实现打印绿色OK和红色FAILED
判断是否有参数,存在为Ok,不存在为FAILED
(1) 编辑脚本文件 shell5_printf.sh
#!/bin/bash
redgreen()
{
if [ $# -ne 0 ]
then
echo -e "\033[32m ok \033[0m"
else
echo -e "\033[31m failed \033[0m"
fi
}
redgreen $*
(2) 运行 bash shell5_printf.sh
2、编写函数,实现判断是否无位置参数,如无参数,提示错误
(1) 编辑脚本文件 shell5_error.sh
#!/bin/bash
err(){
if [ -z "$1" ];then
echo "error"
return 1
else
return 0
fi
}
err $1
(2)运行并测试
3、编写函数实现两个数字做为参数,返回最大值
(1) 编辑脚本文件 vim shell5_numcom.sh
#!/bin/bash
num12(){
expr $2 + $1 &>/dev/null
if [ $# -eq 2 ];then
if [ $1 -gt $2 ];then
echo "$1"
return 1
else
echo "$2"
return 2
fi
else
echo "input error."
fi
}
num12 $1 $2
(2)运行
4、编写函数,实现两个整数位参数,计算加减乘除。
(1) 编辑脚本文件 vim shell5_count.sh
#!/bin/bash
count() {
if [ $# -ne 2 ];then
echo "must have two numbers!"
elif ! expr $1 + $2 &> /dev/null;then
echo "must have number!"
else
echo "$1+$2=$[$1+$2]"
echo "$1-$2=$[$1-$2]"
echo "$1*$2=$[$1*$2]"
echo "$1/$2=$[$1/$2]"
fi
}
(2)运行
5、将/etc/shadow文件的每一行作为元数赋值给数组
(1) 编辑脚本文件 vim shell5_shadow.sh
j=0
for i in `cat /etc/shadow`
do
array[$j]=$i
echo "${array[$j]}"
let j++
done
(2)运行
6、使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
(1) 编辑脚本文件 vim shell5_shell.sh
#!/bin/bash
declare -A array
for i in `cat /etc/passwd | awk -F : '{print $NF}'`
do
let array[$i]++
done
for i in ${!array[*]}
do
echo "$i ${array[$i]}"
done
(2)运行
7、使用关联数组按扩展名统计指定目录中文件的数量
(1) 编辑脚本文件 vim shell5_add.sh
#!/bin/bash
declare -A array
read -p "please input a directory:" pathy
for i in `ls -F $pathy |grep -v /$ |fgrep . | cut -d . -f
do
let array[$i]++
done
for i in ${!array[*]}
do
echo "$i ${array[$i]}"
done
(2)运行