Multiple values can be stored in an array
The shell array is represented by parentheses, and the elements are separated by a "space" symbol.
Syntax format:
Array_name= (value1 value2 ... valuen)
Defining arrays
Array_name[0]=value0
Array_name[1]=value1
Array_name[2]=value2
Reading an array
${array_name[index]}
my_array= (A B "C" D)
echo "first element: ${my_array[0]}"
echo "second element: ${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:
The first element is: A
The second element is: B
The third element is: C
The fourth element is: D
Get all elements in an array
Use @ or * to get all the elements in the array
For example:
my_array= (A B "C" D)
echo "Elements of array: ${my_array[*]}"
echo "Elements of array: ${my_array[@]}"
Execution results
The elements of the array are: A B C D
The elements of the array are: A B C D
Gets the length of the array
y_array= (A B "C" D)
echo "array element number: ${#my_array [*]}"
echo "array element number: ${#my_array [@]}"
Execution results
Number of array elements: 4
Number of array elements: 4
Loop array
For
[[email protected] ~]# array= (a b C 1 2 3)
[[email protected] ~]# echo ${array[@]}
[[Email protected] ~]# a b c d 1 2 3 4
[Email protected] ~]#
For ((i=0;i<${#array [@]};i++))
Do
Echo ${array[i]}
Done
Execution results
A
B
C
1
2
3
Can also be written as
[[email protected] ~]# for a in ${array[@]}
> Do
> Echo $a
> Done
[email protected] ~]# while [$i-lt ${#array [@]}]
> Do
> Echo ${array[$i]}
> Let i++
> Done
Traversal of the shell-array