1、读取/etc/hosts文件,将文件中的每一行作为一个元数赋值给数组
#!/bin/bash
IFS='$ \n'
while read line
do
arry= `echo $line |awk '{print $1}'`
done < /etc/hosts
for i in ${!arry[@]}
do
echo "$i ${arry[$i]}"
done
IFS='$ \t\n'
2、使用read读入创建数组元数的个数,且元数也由用户自己输入,要求使用while来完成
#!/bin/bash
i=1
read -p "请输入要创建数组元数的个数:" num
while [ $num -ge $i ]
do
read -p "输入数组的第$i个元数:"array[$i]
let i++
done
for j in ${!array[@]}
do
echo "$j ${array[$j]}"
done
3、使用read读入创建数组元数的个数,且元数也由用户自己输入,要求使用until来完成
#!/bin/bash
i=1
read -p "请输入要创建数组元数的个数:" num
until [ $i -gt $num ]
do
read -p "输入数组的第$i个元数:"array[$i]
let i++
done
for j in ${!array[@]}
do
echo "$j ${array[$j]}"
done
要求使用for来完成
#!/bin/bash
read -p "请输入要创建数组元数的个数: " num
for i in `seq $num`
do
read -p "输入数组的第$i个元数: " array02[$i]
done
for j in ${!array02[@]}
do
echo "$j ${array02[$j]}"
done
4、使用数组的方式统计某一目录下不同的文件后缀的数量
#!/bin/bash
declare -A file_count
while read file
do
suffix=${file##*.}
let file_count[$suffix]++
done <<< "$(find $1 -type f)" #等价于 done <<< "`find $1 -type f`"
for i in ${!file_count[@]}
do
echo "文件$i的数量是: ${file_count[$i]}"
done
5、使用数组的方式统计某一目录下的普通文件的不同类型的数量,例如:ASCII text的数量,UTF-8
Unicode text的数量,ASCII English text的数量等
#!/bin/bash
#filename: filestat.sh
if [ $# -ne 1 ]; then
echo "Usage `basename $0` DIR "
exit 1
fi
declare -A typecount
while read line
do
filetype=`file -b $line |awk '{print $NF}'`
let typecount[$filetype]++
done <<< "`find $1 -type f -print`"
echo "========== File types and counts =========="
for i in ${!typecount[@]}
do
echo "$i ${typecount[$i]}"
done
6、统计一个存放姓名和性别的文件中不同性别的个数
[root@gaojingbo shell]# cat name_sex.txt
jack F
nammd M
sanmd F
脚本
#!/bin/bash
declare -A sexcount
while read line
do
sextype=`echo $line |awk '{print $2}'`
let sexcount[$sextype]++
done < ./name_sex.txt
echo "========== sex counts =========="
for i in ${!sexcount[@]}
do
echo "$i ${sexcount[$i]}"
done
7、统计不同tcp连接的状态的数量
#!/bin/bash
OFS=$IFS
IFS='
'
declare -A statecount
for line in `ss -ant |grep -vi state`
do
type=`echo $line |awk '{print $1}'`
let statecount[$type]++
done
for i in ${!statecount[@]}
do
echo "$i ${statecount[$i]}"
done
IFS=$OFS