Linux Shell 用法(一)4.数组与关联数组

数组与关联数组

定义数组的方法有很多种。

数组

  1. 可以在单行中使用数值列表来定义一个数组:
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

  1. 列出数组索引 每一个数组元素都有对应的索引。普通数组和关联数组的索引类型不同。我们可以用下面的方法获取数组的索引列表:
 $ echo ${!array_var[*]}

也可以这样

 $ echo ${!array_var[@]}

以先前的fruits_value数组为例,运行如下命令:

 $ echo ${!fruits_value[*]}

orange apple
对于普通数组,这个方法同样可行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章