伏雌摘星阁 2020-04-15
数组的分类
普通数组: 只能使用整数作为数组索引 关联数组: 可以使用字符作为数组索引 元素=索引=下标
普通数组定义
[ ~]# array[0]=shell [ ~]# array[10]=MySQL [ ~]# echo ${array[0]} shell [ ~]# [ ~]# echo ${array[10]} MySQL ----------------- [ ~]# array=(shell MySQL Redis) [ ~]# echo ${array[0]} shell [ ~]# echo ${array[1]} MySQL [ ~]# echo ${array[2]} Redis ---------------- [ ~]# array=(Shell [5]=Docker Redis [10]=MySQL) [ ~]# echo ${array[0]} Shell [ ~]# echo ${array[5]} Docker [ ~]# echo ${array[6]} Redis [ ~]# echo ${array[10]} MySQL
---------------命令定义数组
[ ~]# array=(`ls`) [ ~]# echo ${array[0]} 1.sh [ ~]# echo ${array[1]} 1.txt [ ~]# echo ${array[2]} 2.sh [ ~]# echo ${array[3]} all.sh
常用的定义方式
array=(10.0.0.8 10.0.0.9 10.0.0.32)
取消定义数组
unset array
如何查看数组
[ ~]# echo ${array[0]} # 使用索引查看 [ ~]# echo ${array[*]} # 查看数组中所有的值 shell MySQL Redis [ ~]# echo ${array[@]} # 查看数组中所有的值 shell MySQL Redis [ ~]# echo ${!array[*]} # 查看索引 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
案例:
#!/bin/sh #定义数组 ip=( 10.0.0.1 10.0.0.2 10.0.0.7 10.0.0.8 10.0.0.9 ) #调用数组 for i in ${ip[*]} do ping -c1 -W1 $i &>/dev/null [ $? -eq 0 ] && echo "ping $i 没问题....." || echo "ping $i 不通....." done
遍历索引
#!/bin/sh #定义数组 ip=( 10.0.0.1 0 10.0.0.2 1 10.0.0.7 2 10.0.0.8 3 10.0.0.9 4 ) #调用数组 for i in ${!ip[*]} do ping -c1 -W1 ${ip[$i]} &>/dev/null [ $? -eq 0 ] && echo "ping ${ip[$i]} 没问题....." || echo "ping ${ip[$i]} 不通....." done
[ day5]# declare -A array [ day5]# array[index1]=shell [ day5]# array[index2]=mysql [ day5]# array[index3]=redis [ day5]# [ day5]# echo ${array[index1]} shell [ day5]# echo ${array[index2]} mysql [ day5]# echo ${array[index3]} redis [ day5]# echo ${array[*]} shell mysql redis [ day5]# echo ${array[@]} shell mysql redis [ day5]# echo ${!array[@]} index1 index2 index3 [ day5]# array=([index1]=shell [test]=Redis [index2]=Redis) [ day5]# echo ${array[*]} shell Redis Redis
查看所有的当前shell定义的数组
declare -A
案例:
cat sex.txt
zs m
ls m
zp f
lw f
qq m
ww x
#!/bin/sh #定义数组 declare -A array while read sex do let array[$sex]++ done<sex.txt for i in ${!array[*]} do echo "性别$i 出现了 ${array[$i]} 次" done ---------------- [ day5]# sh array.sh 性别f 出现了 2 次 性别m 出现了 3 次 性别x 出现了 1 次
[ day5]# declare -A array [ day5]# [ day5]# array[m]=1 [ day5]# echo ${array[m]} 1 [ day5]# let array[a]++ [ day5]# let array[a]++ [ day5]# echo ${array[a]} 2 [ day5]# let array[b]++ [ day5]# let array[b]++ [ day5]# let array[b]++ [ day5]# echo ${array[b]} 3 [ day5]# for i in ${!array[*]};do echo $i;done a b m
#!/bin/sh declare -A bash while read line do let bash[`echo $line|awk -F: ‘{print $NF}‘`]++ done</etc/passwd for i in ${!bash[*]} do echo "$i 出现了 ${bash[$i]}次" done
#!/bin/sh declare -A IP while read line do let IP[`echo $line|awk ‘{print $1}‘`]++ done</var/log/nginx/access.log for i in ${!IP[*]} do echo "$i 出现了 ${IP[$i]}次" done