- 定义关联数组
在关联数组中,我们可以用任意的文本作为数组索引。首先,需要使用声明语句将一个变量 定义为关联数组:
declare -A ass_array
声明之后,可以用下列两种方法将元素添加到关联数组中。
使用行内“索引-值”列表:
ass_array=([index1]=val1 [index2]=val2)使用独立的“索引值”进行赋值:
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
对于普通数组,这个方法同样可行。
