1.编写函数,实现打印绿色OK和红色FAILED
判断是否有参数,存在为Ok,不存在为FAILED
[root@cotenos day06]# vim colour.sh
#!/bin/bash
test(){
if [ -z $1 ];then
echo -e "\033[31m FAILED \033[0m"
else
echo -e "\033[32m OK \033[0m"
fi
}
test
执行结果:
[root@cotenos day06]# bash colour.sh
2.编写函数,实现判断是否无位置参数,如无参数,提示错误
[root@cotenos day06]# vim hanshu.sh
#!/bin/bash
test(){
if [ $# -ne 0 ];then
echo "parameters exists"
else
echo" error "
fi
}
read -p " please input parameter: " i
test302 $i
执行:
[root@cotenos day06]# bash hanshu.sh
3.编写函数实现两个数字做为参数,返回最大值
[root@cotenos day06]# vim test3.sh
#!/bin/bash
read -p "请输入两个数:" num1 num2
test3(){
if [ $num1 -gt $num2 ];then
echo "max is $num1"
elif [ $num1 -lt $num2 ];then
echo " max is $num2 "
else
echo " The number are equa"
fi
}
test3 $num1 $num2
运行:
[root@cotenos day06]# bash test3.sh
4.编写函数,实现两个整数位参数,计算加减乘除。
[root@cotenos day06]# vim test4.sh
#!/bin/bash
read -p "please input two number:" num1 num2
test304 (){
expr $num1+$mun2 >&/dev/null
if [ $# -ne 0 ];
then
echo "$num1+$num2=$[$num1+$num2]"
echo "$num1-$num2=$[$num1-$num2]"
echo "$num1*$num2=$[$num1*$num2]"
echo "$num1/$num2=$[$num1/$num2]"
else
echo "is not an integer, please re-enter"
fi
}
test304 $num1 $num2
[root@cotenos day06]# bash test4.sh
please input two number:12 45
12+45=57
12-45=-33
12*45=540
12/45=0
[root@cotenos day06]#
5.将/etc/shadow文件的每一行作为元数赋值给数组
[root@cotenos day06]# vim test5.sh
#!/bin/bash
num=`wc -l </etc/shadow`
for i in `seq $num`
do
array[$i]=`head $i /etc/shadow | tail -l`
done
for i in ${array[*]}
do
echo $i
done
6.使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
[root@cotenos day06]# vim test6.sh
#!/bin/bash
declare -A array
for i in `cut -d: -f 7 /etc/passwd`
do
let array[$i]++
done
for i in ${!array[*]}
do
echo " $i: ${array[$i]} "
done
~
7.使用关联数组按扩展名统计指定目录中文件的数量
[root@cotenos day06]# vim test7.sh
#!/bin/bash
read -p "pleace input filename:" filename
declare -A array
for i in `ls $filename | fgrep '.' | cut -d . -f 2`
do
let array[$i]++
done
for i in ${!array[*]}
do
echo "$i: ${array[$i]}"
done