数组与关联数组

简介:

数组允许脚本利用索引将数据集合保存为独立的条目。Bash支持普通数组和关联数组,前者使用整数作为数组索引,后者使用字符串作为数组索引。当数据以数字顺序组织的时候,应该使用普通数组,例如一组连续的迭代。当数据以字符串组织的时候,关联数组就派上用场了,例如主机名称。本节会介绍普通数组和关联数组的用法

1.定义数组

(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

2.定义关联数组:

在关联数组中,我们可以用任意的文本作为数组索引。首先,需要使用声明语句将一个变量定义为关联数组:

declare / typeset:

declare 或 typeset 是一样的功能,就是在『宣告变量的类型』。如果使用 declare 后面并没有接任何参数,那么 bash 就会主动的将所有的变量名称与内容通通叫出来

$ 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

3.列出数组索引

每一个数组元素都有对应的索引。普通数组和关联数组的索引类型不同。我们可以用下面的
方法获取数组的索引列表:

$ echo ${!array_var[*]}

也可以这样

$ echo ${!array_var[@]}

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

$ echo ${!fruits_value[*]}
orange apple

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

posted @ 2021-02-23 15:23  (◓3◒)  阅读(135)  评论(0)    收藏  举报