Good programmers Big Data sharing Shell in the array to explain , the array is Shell very important part, which means the index multiple independent data is stored as a set. Array divided into ordinary and associative arrays, the array can use ordinary integers as an array index, array and associated array index can be used as strings.
Array definition
A pair of parentheses indicate an array, separated by a space character between the array elements, as shown below:
array1=(1 2 3)
array2=("xiaoqian" "xiaofeng")
Further, arrays can also be defined as a set of index - as a value, as shown below:
array3 [0] = 1
array3 [1] = 2
array3 [4] = 3
Note that the index values may not be continuous, and the scope is not limited.
It is defined above normal array, first need to use an associative array declaration statement declared before defined, as shown below:
declare -A array4
array4 = ([xiaoqian] = 18 [xiaofeng] = 19)
declare -A array5
array5 [xiaoqian] = 18
array5 [xiaofeng] = 20
Operation array
After the array is defined, some operations may be, as shown below:
1. Get array length
echo $ {# array1 [*] } # Output 3
echo $ {# array4 [@] } # Output 2
Above 2 methods can obtain the length of the array, and a similar method to obtain the string length. Further, the acquisition of the array element length of the individual can use the following method:
echo $ {# array2 [0] } # output 8
echo $ {# array5 [xiaoqian] } # Output 2
2. get the array element values
echo $ {array1 [0]} # Output 1
echo $ {array4 [xiaoqian]} # output 18
The above statement is a single element of the array value acquisition, if the need to obtain all of the array element values may be used @ or * sign, as shown below:
echo $ {array1 [*]} # Output 123
echo $ {array4 [@]} # output 1918
3. To obtain the array index
echo $ {! array1 [*] } # Output 012
echo ${!array4[@]} # 输出xiaofeng xiaoqian
Above 2 methods can get all indexed array.