數組與關聯數組
定義數組的方法有很多種。
數組
- 可以在單行中使用數值列表來定義一個數組:
array_var=(test1 test2 test3 test4)
#這些值將會存儲在以0爲起始索引的連續位置上 另外,還可以將數組定義成一組“索引值”:
array_var[0]="test1"
array_var[1]="test2"
array_var[2]="test3"
array_var[3]="test4"
array_var[4]="test5"
array_var[5]="test6"
2.打印出特定索引的數組元素內容:
echo ${array_var[0]}
test1
index=5
echo ${array_var[$index]}
test6
3.以列表形式打印出數組中的所有值:
$ echo ${array_var[*]}
test1 test2 test3 test4 test5 test6
也可以這樣使用:
$ echo ${array_var[@]}
test1 test2 test3 test4 test5 test6
4.打印數組長度(即數組中元素的個數):
$ echo ${#array_var[*]}6
關聯數組
首先,需要使用聲明語句將一個變量 定義爲關聯數組:
$ declare -A ass_array
聲明之後,可以用下列兩種方法將元素添加到關聯數組中。
1.使用行內“索引-值”列表:
$ ass_array=([index1]=val1 [index2]=val2)
2.使用獨立的“索引-值”進行賦值:
$ ass_array[index1]=val1
$ ass_array'index2]=val2
舉個例子,試想如何用關聯數組爲水果制定價格:
$ declare -A fruits_value
$ fruits_value=([apple]='100 dollars' [orange]='150 dollars')
用下面的方法顯示數組內容:
$ echo "Apple costs ${fruits_value[apple]}"
Apple costs 100 dollars
- 列出數組索引 每一個數組元素都有對應的索引。普通數組和關聯數組的索引類型不同。我們可以用下面的方法獲取數組的索引列表:
$ echo ${!array_var[*]}
也可以這樣
$ echo ${!array_var[@]}
以先前的fruits_value數組爲例,運行如下命令:
$ echo ${!fruits_value[*]}
orange apple
對於普通數組,這個方法同樣可行。