关联数组
注意:先声明关联数组
一、定义关联数组
方法一
#一次赋一值
#数组名[索引]=变量值
[root@localhost ~]# declare -A ass_array1
[root@localhost ~]# ass_array1[index1]=pear
[root@localhost ~]# ass_array1[index2]=apple
[root@localhost ~]# ass_array1[index3]=orange
[root@localhost ~]# ass_array1[index4]=peach
[root@localhost ~]# echo ${ass_array1[*]} #查看
peach pear apple orange
方法二
#一次赋多个值
[root@localhost ~]# declare -A ass_array2
[root@localhost ~]# ass_array2=([index1]=tom [index2]=jack [index3]=alice [index4]="bash shell")
[root@localhost ~]# echo ${ass_array2[*]} #查看
bash shell tom jack alice
[root@localhost ~]# echo ${!ass_array2[*]}
index4 index1 index2 index3
[root@localhost ~]# echo ${#ass_array2[*]}
4
二、查看数组
[root@localhost ~]# declare -A
declare -A ass_array1='([index4]="peach" [index1]="pear" [index2]="apple" [index3]="orange" )'
declare -A ass_array2='([index4]="bash shell" [index1]="tom" [index2]="jack" [index3]="alice" )'
三、访问数组元素
[root@localhost ~]# echo ${ass_array2[index2]} #访问数组中的第二个元素
[root@localhost ~]# echo ${ass_array2[@]}
[root@localhost ~]# echo ${ass_array2[*]} #访问数组中所有元素
[root@localhost ~]# echo ${!ass_array2[@]} #获得数组元素的个数
[root@localhost ~]# echo ${#ass_array2[@]} #获得数组元素的索引