1. 程式人生 > >【Linux】數組與關聯數組

【Linux】數組與關聯數組

variable spa 語法 col div 報錯 ria declare right

數組

數組的定義:

variable=(arg1 arg2 arg3 …)

中間用空格分開,數組的下標從0開始

1.獲取下標為n的元素

variable[n]

不存在數組溢出的情況,如果下標n>=數組長度,那麽為空,不會報錯。

[root@localhost test]# var=(1 2 3)
[root@localhost test]# echo ${var[0]}
1

2.獲取數組長度

${#var[@]}或者${#var[*]}

[root@localhost test]# echo ${#var[@]}
3
[root@localhost test]# echo
${#var[*]} 3

3.循環遍歷數組

語法:

for i in ${var[@]};do

#do something…

done

也可以將上述@換成*

關聯數組

在關聯數組中,我們可以用任意的文本作為數組索引

[root@localhost test]# declare -A Arr
[root@localhost test]# Arr=([pos1]=zhangsan [pos2]=Lisi
[root@localhost test]# echo ${Arr[pos1]}
zhangsan

也可以使用獨立的索引對數組賦值

[root@localhost test]# Arr[pos3]=Wangwu

列出數組所以的索引值(關聯數組與普通數組都通用)

[root@localhost test]# echo ${!Arr[@]}
pos2 pos3 pos1
[root@localhost test]# echo ${!Arr[*]}
pos2 pos3 pos1

【Linux】數組與關聯數組