1. 程式人生 > 實用技巧 >shell普通陣列與關聯陣列對比

shell普通陣列與關聯陣列對比

關聯陣列

[root@centos17 shell]# cat shells_count.sh 
#!/bin/bash
#login shell counts 

declare -A shells

while read line
do
	type=`echo $line|awk -F":" '{print $NF}'`
	let shells[$type]++
done < /etc/passwd

#echo ${!shells[@]} ${shells[@]}
for i in ${!shells[@]} 
do
	printf "%-20s %3s\n" $i ${shells[$i]}		
done
[root@centos17 shell]# sh shells_count.sh 
/sbin/nologin         25
/bin/sync              1
/bin/bash              4
/sbin/poweroff         1
/sbin/shutdown         1
/sbin/halt             1
/usr/sbin/poweroff     1
[root@centos17 shell]# 

  

普通陣列

[root@centos17 shell]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.160 nas
192.168.5.105 centos17
[root@centos17 shell]# sh hosts.sh 
1:127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
2:::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
3:192.168.0.160 nas
4:192.168.5.105 centos17
[root@centos17 shell]# cat hosts.sh
#!/bin/bash
#hosts display

OLD_IFS=$IFS
#IFS=$`\n`
IFS=$'\n'

for i in `cat /etc/hosts`
do
	hosts[++a]=$i
done


for j in ${!hosts[@]}
do
	echo "$j:${hosts[j]}" 或者echo "$j:${hosts[$j]}"
done
[root@centos17 shell]# 

 

小結:

  普通陣列:呼叫陣列值時,${hosts[$j]}與${hosts[j]}等價,索引前無需新增$符號。

  關聯陣列:呼叫陣列值時,只能使用${shells[$i]},索引前必須新增$符號。因為關聯陣列的索引不能為數字。