#普通数组:只能使用整数作为数组索引
#普通数组
一次赋一个值
array1[0]=pear
array1[1]=apple
一次赋多个值
array2=(tom jack alice)
array3=(`cat /etc/passwd`) #会将文件中的每一行做为一个值赋值给数组,但是如果有空格,会按空格分割,有空格需重新定义分隔符
array4=(tom jack alice "bash shell")
colors=($red $blue $green $recolor)
array5=(1 2 3 4 5 6 "linux shell" [20]=saltstack) #可以指定下标赋值
#关联数组:可以使用字符串作为数组索引
#关联数组
info=([name]=tianyu [sex]=male [age]=36 [height]=170)
echo ${info[age]}
echo ${array1[0]} #访问数组中第一个元素
echo ${array1[@]} #访问数组中所有元素 等同于echo ${array1[*]}
echo ${#array1[@]} #统计数组元素的个数
echo ${!array1[@]} #获取数组元素的索引
echo ${array1[@]:1} #从数组下标1开始
echo ${array1[@]:1:2} #从数组下标1开始,访问两个元素
declare -a #查看数组
#while循环遍历数组元素
#!/usr/bin/bash
while read line
do
hosts[++i]=$line
done </etc/hosts
echo "hosts first: ${hosts[1]}"
echo
for i in ${!hosts[@]}
do
echo "$i: ${hosts[i]}"
done
#for循环读取数据到数组 需重新定义文件分割符
#!/usr/bin/bash
OLD_IFS=$IFS
IFS=$'\n'
for line in `cat /etc/hosts`
do
hosts[++j]=$line
done
for i in ${!hosts[@]}
do
echo "$i: ${hosts[i]}"
done
IFS=$OLD_IFS
#用数组统计每个分组的数量
#!/usr/bin/bash
declare -A sex
echo "jm m" > sex.txt
while read line
do
type=`echo $line | awk '{print $2}'`
let sex[$type]++
done < sex.txt
for i in ${!sex[@]}
do
echo "$i: ${sex[$i]}"
done
#遍历数组统计不同shell类型数量
#!/usr/bin/bash
#awk -F":" '{print $NF}' /etc/passwd |sort |uniq -c #等价于这条命令
declare -A shells
while read line
do
type=`echo $line |awk -F":" '{print $NF}'`
let shells[$type]++
done </etc/passwd
for i in ${!shells[@]}
do
echo "$i: ${shells[$i]}"
done
#统计tcp连接状态数量
#!/usr/bin/bash
declare -A status
while :
do
type=`ss -an |grep :80 |awk '{print $2}'`
for i in $type
do
let status[$i]++
done
for j in ${!status[@]}
do
echo "$j: ${status[$j]}"
done
sleep 1
clear
done