The shell is much more programmatic in terms of programming than Windows batch processing, both in loops and operations.
Bash supports one-dimensional arrays (which do not support multidimensional arrays) and does not limit the size of arrays. Similar to the C language, the subscript of an array element is numbered starting with 0. Gets the elements in the array to take advantage of subscript, the subscript can be an integer or an arithmetic expression whose value should be greater than or equal to 0.
Defining arrays
In the shell, the array is represented by parentheses, and the elements of the array are separated by a "space" symbol. The general form of the definition array is:
Array_name= (value1 ... valuen)
For example:
Array_name= (value0 value1 value2 value3)
Or
Array_name=( value0 value1 value2 value3 )
You can also define individual components of an array individually:
array_name[0]=value0 array_name[1]=value1 array_name[2]= value2
You can not use successive subscripts, and there is no limit to the range of subscripts.
Reading an array
The general format for reading array element values is:
${array_name[index]}
For example:
valuen=${array_name[2]}
#!/bin/bashname[0]="Zara"name[1]="Qadir"name[2]="Mahnaz"name[3]="Ayan"name[4]="Daisy"Echo "First Index: ${name[0]}"Echo "Second Index: ${name[1]}"
Run script, Output:
$ bash Array. SH First Index:zarasecond Index:qadir
Use @ or * to get all the elements in the array, for example:
${array_name[*]} ${array_name[@]}
#!/bin/bashname[0]="Zara"name[1]="Qadir"name[2]="Mahnaz"name[3]="Ayan"name[4]="Daisy"Echo "First Index: ${name[*]}"Echo "Second Index: ${name[@]}"
Operation Result:
$ bash array2. SH First Index:zara Qadir Mahnaz Ayan daisysecond Index:zara Qadir Mahnaz Ayan Daisy
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/bashname[0]="Zara"name[1]="Qadir"name[2]="Mahnaz"name[3]="Ayan"name[4]="Daisy"Echo "First Index: ${name[*]}"Echo "Second Index: ${name[@]}"#取得数组元素的个数length=${#NAME [@]}Echo-E $length"\ n"#或者length=${#NAME [*]}Echo-E $length"\ n"#取得数组单个元素的长度lengthn=${#NAME [0]}Echo-E $lengthn"\ n"
Operation Result:
First Index:zara Qadir Mahnaz Ayan daisysecond Index:zara Qadir Mahnaz Ayan Daisy 5 5 4
Shell array: Definition of shell array, array length