数组容许脚本利用索引将数据集合保存为独立的条目。Bash支持普通数组和关联数组,前者
使用整数做为数组索引,后者使用字符串做为数组索引。当数据以数字顺序组织的时候,应该使
用普通数组,例如一组连续的迭代。当数据以字符串组织的时候,关联数组就派上用场了,例如
主机名称。node
[root@dns-node2 tmp]# array_var=(test1 test2 test3) [root@dns-node2 tmp]# echo ${array_var[0]} test1
另外,还能够将数组定义成一组“索引-值”python
[root@dns-node2 tmp]# array_var[0]="test0" [root@dns-node2 tmp]# array_var[0]="test3" [root@dns-node2 tmp]# array_var[2]="test2" [root@dns-node2 tmp]# array_var[3]="test0" [root@dns-node2 tmp]# echo ${array_var} test3 [root@dns-node2 tmp]# echo ${array_var[3]} test0 [root@dns-node2 tmp]# echo ${array_var[2]} test2 [root@dns-node2 tmp]# echo ${array_var[1]} test2 [root@dns-node2 tmp]# echo ${array_var[0]} test3
打印这个数组下面全部的值数组
[root@dns-node2 tmp]# echo ${array_var[*]} test3 test2 test2 test0 [root@dns-node2 tmp]# echo ${array_var[@]} test3 test2 test2 test0
打印数组的长度code
[root@dns-node2 tmp]# echo ${#array_var[@]} 4
在关联数组中,咱们能够用任意的文本做为数组索引。首先,须要使用声明语句将一个变量,这个实际上是Map,在python里面叫作字典,在go里面叫作map。
定义为关联数组索引
[root@dns-node2 tmp]# declare -A ass_array [root@dns-node2 tmp]# ass_array=([i1]=v1 [i2]=v2)
[root@dns-node2 tmp]# ass_array=[i1]=v1 [root@dns-node2 tmp]# ass_array=[i2]=v2
取值dns
[root@dns-node2 tmp]# echo ${ass_array[i1]} v1 [root@dns-node2 tmp]# echo ${ass_array[i2]} v2 [root@dns-node2 tmp]# echo ${ass_array[*]} # 取value v2 v1 [root@dns-node2 tmp]# echo ${ass_array[@]} # 取value v2 v1 [root@dns-node2 tmp]# echo ${!ass_array[@]} #取key i2 i1