1、编写函数,实现打印绿色 OK 和红色 FAILED;判断是否有参数,存在为OK,不存在为FAILED。
脚本文件:
2、编写函数,实现判断是否无位置参数,如无参数,提示错误。
脚本文件:
#!/bin/bash
func() {
if [ -z "$1" ]
then
echo "错误"
fi
}
func $1
3、编写函数实现两个数字做为参数,返回最大值
脚本文件:
#!/bin/bash
max() {
read -p "first num: " num1
read -p "second num: " num2
if [ $num1 -ge $num2 ]
then
echo "$num1"
else
echo "$num2"
fi
}
max
4、编写函数,实现两个整数位参数,计算加减乘除。
脚本文件:
#!/bin/bash
read -p "first num: " num1
read -p "second num: " num2
calculate() {
num1=$1
num2=$2
# 提取整数部分
int1=${num1%.*}
int2=${num2%.*}
add=$(( int1+int2 ))
sub=$(( int1-int2 ))
mul=$(( int1*int2 ))
# ne ===> 判断两个数是否不相等
if [ $int2 -ne 0 ];
then
div=$(( int1/int2 ))
else
div="除数为0,除法运算不成立!!!"
fi
echo "加法:$add"
echo "减法:$sub"
echo "乘法:$mul"
echo "除法:$div"
}
calculate $num1 $num2
5、将/etc/shadow文件的每一行作为元数赋值给数组
脚本文件:
#!/bin/bash
i=0
declare -A array
for line in `cat /etc/shadow`
do
array[$i]=$line
i=`expr $i + 1`
done
echo ${array[*]}
6、使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
脚本文件:
#!/bin/bash
i=0
declare -A array
for line in `cat /etc/passwd | cut -d : -f 7 | sort -s | uniq -c |sort -n`
do
array[$i]=$line
i=`expr $i + 1`
done
echo ${array[*]}
7、使用关联数组按扩展名统计指定目录中文件的数量
#!/bin/bash
i=0
declare -A array
for line in `cat /etc/passwd | cut -d : -f 2,3 | sort -s | uniq -c`
do
array[$i]=$line
i=`expr $i + 1`
done
echo ${array[*]}