Shell array


Multiple values ​​can be stored in the array. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no need to define the array size during initialization (similar to PHP).

Similar to most programming languages, the subscripts of array elements start from 0.

Shell arrays are represented by brackets, and elements are separated by "space" symbols. The syntax format is as follows:

array_name=(value1 ... valuen)

Example

#!/bin/bash
# author:php中文网
# url:www.php.cn

my_array=(A B "C" D)

We can also use subscripts to define arrays :

array_name[0]=value0
array_name[1]=value1
array_name[2]=value2

Read array

The general format for reading array element values ​​is:

${array_name[index]}

Example

#!/bin/bash
# author:php中文网
# url:www.php.cn

my_array=(A B "C" D)

echo "第一个元素为: ${my_array[0]}"
echo "第二个元素为: ${my_array[1]}"
echo "第三个元素为: ${my_array[2]}"
echo "第四个元素为: ${my_array[3]}"

Execute the script, the output result is as follows :

$ chmod +x test.sh 
$ ./test.sh
第一个元素为: A
第二个元素为: B
第三个元素为: C
第四个元素为: D

Get all elements in the array

Use @ or * to get all elements in the array, for example:

#!/bin/bash
# author:php中文网
# url:www.php.cn

my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D

echo "数组的元素为: ${my_array[*]}"
echo "数组的元素为: ${my_array[@]}"

Execute the script, the output result is as follows:

$ chmod +x test.sh 
$ ./test.sh
数组的元素为: A B C D
数组的元素为: A B C D

Get the length of the array

The method of getting the length of the array is the same as the method of getting the length of the string, for example:


#!/bin/bash
# author:php中文网
# url:www.php.cn

my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D

echo "数组元素个数为: ${#my_array[*]}"
echo "数组元素个数为: ${#my_array[@]}"

Execute Script, the output result is as follows:

$ chmod +x test.sh 
$ ./test.sh
数组元素个数为: 4
数组元素个数为: 4