Multiple values can be stored in an array. The Bash Shell supports only one-dimensional arrays (which do not support multidimensional arrays) and does not need to define the array size when initializing (similar to PHP).
Like most programming languages, the subscript of an array element starts with 0.
The Shell array is represented by parentheses, and the elements are separated by a "space" symbol, with the following syntax:
Array_name= (value1 ... valuen)
Instance
#!/bin/bashmy_array= (A B "C" D)
We can also use subscripts to define arrays:
Array_name[0]=value0array_name[1]=value1array_name[2]=value2
Reading an array
The general format for reading array element values is:
${array_name[index]}
Instance
#!/bin/bashmy_array= (a B "C" D) echo "The first element is: ${my_array[0]}" echo "The second element is: ${my_array[1]}" echo "The third element is: ${my_array[2]}" echo "fourth element: ${my_array[3]}"
Execute the script with the output as follows:
$ chmod +x test.sh $./test.sh The first element is: a the second element is: b The third element is: c The fourth element is: D
Gets all the elements in the array
Use @ or * to get all the elements in the array, for example:
#!/bin/bashmy_array[0]=amy_array[1]=bmy_array[2]=cmy_array[3]=decho "Elements of Array: ${my_array[*]} The elements of the" echo "Array are: ${my_ array[@]} "
Execute the script with the output as follows:
$ chmod +x test.sh $. The elements of the/test.sh array are: A B c D array with elements of: a B c D
Gets the length of the array
The method of getting the length of the array is the same as getting the string length, for example:
#!/bin/bashmy_array[0]=amy_array[1]=bmy_array[2]=cmy_array[3]=decho "array element number: ${#my_array [*]}" echo "array elements are: ${#my _array[@]} "
Execute the script with the output as follows:
$ chmod +x test.sh $. The number of elements in the/test.sh array is: 4 the number of array elements is: 4
This article is from the "Wind Trace _ Snow Tiger" blog, please be sure to keep this source http://snowtiger.blog.51cto.com/12931578/1941331
Shell--4, Shell array