Shell array

Multiple values can be stored in an array. B ash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no need to define array sizes (similar to PHP) when initializing.

Like most programming languages, the underling of array elements starts at 0.

The shell array is represented by parentheses, and the elements are split by the "space" symbol, in the following syntax format:

array_name=(value1 ... valuen)

Instance

#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.cn

my_array=(A B "C" D)

We can also use the underse label to define arrays:

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

Read the array

The general format for reading array element values is:

${array_name[index]}

Instance

#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.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 and the output looks like this:

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

Gets all the elements in the array

You can get all the elements in the array, such as:

#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.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 and the output looks like this:

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

Gets the length of the array

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

#!/bin/bash
# author:W3Cschool教程
# url:www.w3cschool.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 and the output looks like this:

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