One, array, and associative arrays
An array is an important part of a shell script that stores separate, independent data as a collection by means of an index. A normal array can only use integers as an array index, and associative arrays not only use integers as indexes, but also strings. In general, it is easier to understand the use of strings for indexing. Bash introduced an associative array from 4.0 onwards.
Second, the definition of printing normal array
There are several methods of array:
Copy Code code as follows:
#在一行上列出所有元素
Array_var= (1 2 3 4 5 6)
#以 "index-value" in the form of a list
array_var[0]= "Test1"
array_var[1]= "Test2"
array_var[2]= "Test3"
Note: The first method uses parentheses, otherwise the error will be followed.
There are several methods of array elements:
Copy Code code as follows:
echo ${array_var[0]} #输出结果为 test1
index=2
echo ${array_var[$index]} #输出结果为 test3
echo ${array_var[*]} #输出所有数组元素
echo ${array_var[@]} #输出所有数组元素
echo ${#array_var [*]} #输出值为 3
Note: In Ubuntu 14.04, the shell script starts with #!/bin/bash and executes the script in the form of Bash test.sh.
Defining print associative arrays
Defining an associative array
In an associative array, you can use any text as an array index. When defining an associative array, you first need to declare a variable as an associative array using a declaration statement before you can add elements to the array, as follows:
Copy Code code as follows:
Declare-a Ass_array #声明一个关联数组
Ass_array= (["Index1"]=index1 ["Index2"]=index2) #内嵌 "index-value" list method
ass_array["Index3"]=index3
ass_array["Index4"]=index4
echo ${ass_array["Index1"]} #输出为index1
echo ${ass_array["Index4"]}
echo ${!ass_array[*]} #输出索引列表
echo ${!ass_array[@]} #输出索引列表
Note: For a normal array, you can still list the index list using the above method, and you cannot add a dollar sign before declaring an associative array and adding an array element