shell 函数和数组作业
1、编写函数,实现打印绿色OK和红色FAILED,判断是否有参数,存在为Ok,不存在为FAILED
2、编写函数,实现判断是否无位置参数,如无参数,提示错误
3、编写函数实现两个数字做为参数,返回最大值
4、编写函数,实现两个整数位参数,计算加减乘除
5、将/etc/shadow文件的每一行作为元数赋值给数组
6、使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
7、使用关联数组按扩展名统计指定目录中文件的数量
1、编写函数,实现打印绿色OK和红色FAILED,判断是否有参数,存在为Ok,不存在为FAILED
[root@localhost test]# vim 1.sh
#!/bin/bash
face(
{if [ -z "$1" ];thenecho -e "\\e[1;32m OK \\e[0m"elseecho -e "\\e[1;31m FLASE \\e[0m"fi
}
face $1
2、编写函数,实现判断是否无位置参数,如无参数,提示错误
[root@localhost test]# vim 2.sh
#!/bin/bash
face()
{if [ "$1" -gt 0 ];thenecho "有位置参数"elseecho "无位置参数"fi
}
face $#
[root@localhost test]# bash 2.sh 1
有位置参数
[root@localhost test]# bash 2.sh
无位置参数
3、编写函数实现两个数字做为参数,返回最大值
[root@localhost test]# vim 3.sh
#!/bin/bash
read -p "输入两个整数:" a b
[ -z $a -o -z $b ] && read -p "输入不能为空,重新输入:" a b
expr $a + 1 &>/dev/null
err1=$?
expr $b + 1 &>/dev/null
err2=$?
[ "$err1" -ne 0 -o "$err2" -ne 0 ] && read -p "输入错误,重新输入:" a b
face()
{if [ "$1" -gt "$2" ];thenecho "$1"elseecho "$2"fi
}
face $a $b
[root@localhost test]# bash 3.sh
输入两个整数:34 34
34
[root@localhost test]# bash 3.sh
输入两个整数:34 24
34
4、编写函数,实现两个整数位参数,计算加减乘除
[root@localhost test]# vim 4.sh
#!/bin/bash
read -p "输入两个整数:" a b
[ -z $a -o -z $b ] && read -p "输入不能为空,重新输入:" a b
expr $a + 1 &>/dev/null
err1=$?
expr $b + 1 &>/dev/null
err2=$?
[ "$err1" -ne 0 -o "$err2" -ne 0 ] && read -p "输入错误,重新输入:" a b
face()
{echo "$1+$2="$[$1+$2]echo "$1-$2="$[$1-$2]echo "$1*$2="$[$1*$2]echo "$1/$2="$[$1/$2]
}
face $a $b
[root@localhost test]# bash 4.sh
输入两个整数:
输入不能为空,重新输入:a d
输入错误,重新输入:8 4
8+4=12
8-4=4
8*4=32
8/4=2
5、将/etc/shadow文件的每一行作为元数赋值给数组
[root@localhost test]# vim 5.sh
#!/bin/bash
i=0
while read line
doarray[$i]=$linelet i++
done < /etc/shadowfor i in ${array[*]}
doecho $i
done
6、使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
[root@localhost test]# vim 6.sh
#!/bin/bash
shell=`cut -d : /etc/passwd -f7 | sort -n | uniq`
file=`cut -d : /etc/passwd -f7 | sort -n`
declare -A array
for i in $shell
dok=0for j in $filedoif [ "$i" = "$j" ];thenlet k++fiarray[$i]=$kdone
done
for i in $shell
doecho "array[$i]="${array[$i]}
done
[root@localhost test]# bash 6.sh
array[/bin/bash]=23
array[/bin/false]=1
array[/bin/sync]=1
array[/sbin/halt]=1
array[/sbin/nologin]=33
array[/sbin/shutdown]=1
array[/usr/sbin/nologin]=2
7、使用关联数组按扩展名统计指定目录中文件的数量
[root@localhost test]# vim 7.sh
#!/bin/bash
read -p "输入目录文件:" path
[ -z $path ] && read -p "输入错误,重新输入:" path
shell=`ls $path | cut -d . -f2 | sort -n | uniq`
declare -A array
for i in $shell
dok=0for j in `ls $path | cut -d . -f2`doif [ "$i" = "$j" ];thenlet k++fiarray[$i]=$kdone
done
for i in $shell
doecho "array[$i]="${array[$i]}
done