Shell introduced an array of
Array regarded as a special data structure, the data item may be elements of an array may be obtained for each array element values by the array index.
Typical usage scenario array is aggregated with the same type of element. Since the variables are weakly Shell type, the elements of the array which are not necessarily of the same type.
Note: Shell in the array supports only one-dimensional arrays, but there is no limit on the number of elements of the index array elements also start from zero.
Array definition
Define the format of the array: declare -a name of the array
For example: declare -a testarr # define an array testarr
testarr [0] = 10 # assign the first element
testarr [1] = "hello" # assign the second element
# Array definition the time when the assignment
declare -a testarr = (10, 'hello') is equivalent to testarr = (10, 'hello')
testarr [2] = 20 # add elements
# Discontinuous assignment
testarr1 = ([1] = 10 [3] = 30 [5] = 50)
Operation array
1, an array of values
The following format: name $ {array [index]}
For example: echo $ {testarr [0]}
echo $ {testarr [@]} # acquired output values of all elements separated by a space element value
echo $ {testarr [*]} # get values for all the output element is a whole string
2, the array length
Methods as below:
echo $ {# testarr [@]} # Get the number of array elements
echo $ {# testarr [*]} # Get the number of array elements
echo $ {# testarr [0]} # Get the length of an element of the array
3, the array taken
echo ${testarr[@]:1:2}
# Get the element array index value is 1, 2
echo ${testarr[2]:0:2}
Get the array index # 2 is an element taken from the zero value character 2 consecutive characters
4, connected to the array
testarr2 = {$ {testarr [@]} $ {testarr1 [@]}} # merge array
5, the replacement elements: an element value is replaced with another value within the array
testarr=($testarr[@]/hello/helloworld)
6, or cancel the array elements
Cancel array unset $ testarr #
unset $ testarr [0] # element array canceled
Reproduced in: https: //www.jianshu.com/p/b29939039408