Shell is much more powerful than Windows batch processing in programming, whether in loops or operations.
Bash supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no limit to the size of the array. Similar to the C language, the subscripts of array elements are numbered from 0. To get the elements in the array, use the subscript. The subscript can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.
Defining an Array
In the Shell, an array is represented by parentheses, and the array elements are separated by a "space" symbol. The general form of defining an array is:
array_name=(value1 ... valuen)
For example:
array_name=(value0 value1 value2 value3)
or
Reading an Array The general format for
reading an array element value is:
${array_name[index]}
For example:
valuen=${array_name[2]}
For example:
of an Array The method for getting the length of an array is the same as for getting the length of a string, for example:
Bash supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no limit to the size of the array. Similar to the C language, the subscripts of array elements are numbered from 0. To get the elements in the array, use the subscript. The subscript can be an integer or an arithmetic expression, and its value should be greater than or equal to 0.
Defining an Array
In the Shell, an array is represented by parentheses, and the array elements are separated by a "space" symbol. The general form of defining an array is:
array_name=(value1 ... valuen)
For example:
array_name=(value0 value1 value2 value3)
or
array_name=( value0 value1 value2 value3 )It is also possible to define the individual components of the array individually:
array_name[0]=value0 array_name[1]=value1 array_name[2]=value2Consecutive subscripts may not be used, and there is no limit to the range of subscripts.
Reading an Array The general format for
reading an array element value is:
${array_name[index]}
For example:
valuen=${array_name[2]}
For example:
#!/bin/sh NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Index: ${NAME[0]}" echo "Second Index: ${NAME[1]}"Running the script, output:
$./test.sh First Index: Zara Second Index: QadirUse @ or * to get all elements in an array, for example:
${array_name[*]} ${array_name[@]}for example:
#!/bin/sh NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Method: ${NAME[*]}" echo "Second Method: ${NAME[@]}"Running the script, output:
$./test.sh First Method: Zara Qadir Mahnaz Ayan Daisy Second Method: Zara Qadir Mahnaz Ayan DaisyGetting the Length
of an Array The method for getting the length of an array is the same as for getting the length of a string, for example:
# Get the number of array elements length=${#array_name[@]} # or length=${#array_name[*]} # Get the length of a single element of the array lengthn=${#array_name[n]}