数组借助索引将多个独立的数据存储为一个集合,是shell脚本非常重要的组成部分。
[root@localhost linshi]# cat passwd3
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
[root@localhost linshi]#
[root@localhost linshi]# awk -F: '{user[j++]=$1}END{for(i in user){print i,user[i]}}' passwd3
4 lp
0 root
1 bin
2 daemon
3 adm
[root@localhost linshi]# awk -F: '{user[++j]=$1}END{for(i=1;i<=j;i++){print i,user[i]}}' passwd3
1 root
2 bin
3 daemon
4 adm
5 lp
[root@localhost linshi]#
[root@localhost linshi]# awk -F: '{shells[$NF]++} END{for( i in shells ){ print i,shells[i] }}' passwd
/bin/sync 1
/bin/bash 1
/sbin/nologin 16
/sbin/halt 1
/sbin/shutdown 1
[root@localhost linshi]#
[root@localhost linshi]# sh count_shells.sh
/sbin/nologin: 16
/bin/sync: 1
/bin/bash: 1
/sbin/shutdown: 1
/sbin/halt: 1
[root@localhost linshi]# cat count_shells.sh
#!/bin/bash
declare -A shells
while read line
do
type1=$(echo $line | awk -F: '{print $NF}')
let shells[$type1]++
done < passwd
for i in ${!shells[@]}
do
echo $i: ${shells[$i]}
done
[root@localhost linshi]#
######按照数组索引进行便遍历,格式如下:
awk -F "break" ‘{arrayname[index]=arrayvalue} END{for(i in arrayname){print i,arrayname[index]}}’ filename
#######按照数组元素个数进行遍历,格式如下
awk -F “break” '{arrayname[index]=arrayvalue} END{for(i=1;i<=index;i++){print i,arrayname[i]}}' filename