关联数组

[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]},索引前必须添加$符号。因为关联数组的索引不能为数字。


 

相关文章:

  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2021-07-13
  • 2021-07-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2023-02-16
  • 2022-12-23
相关资源
相似解决方案