shell基础知识之数组

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

普通数组

  1. 可以在单行中使用数值列表来定义一个数组
[root@dns-node2 tmp]# array_var=(test1 test2 test3)
[root@dns-node2 tmp]# echo ${array_var[0]}
test1

另外,还可以将数组定义成一组“索引-值”

[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

打印数组的长度

[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

取值

[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

原文地址:https://www.cnblogs.com/liaojiafa/p/11462131.html