Latest web development tutorials

Shell array

The array can store multiple values. Bash Shell supports only one-dimensional arrays (does not support multidimensional arrays), no need to define the size of the array is initialized (similar to PHP).

Like most programming languages, the subscript of array elements starting from zero.

Shell use parentheses to denote an array element with the "space" symbol separated, syntax is as follows:

array_name=(value1 ... valuen)

Examples

#!/bin/bash
# author:本教程
# url:www.w3big.com

my_array=(A B "C" D)

We can also define arrays using the following standard:

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

Read array

The general format is read array element value:

${array_name[index]}

Examples

#!/bin/bash
# author:本教程
# url:www.w3big.com

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 is as follows:

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

Gets an array of all the elements

Use the @ or * can get an array of all the elements, such as:

#!/bin/bash
# author:本教程
# url:www.w3big.com

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 is as follows:

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

Get length of the array

Gets an array of lengths of string length and get the same way, for example:

#!/bin/bash
# author:本教程
# url:www.w3big.com

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 is as follows:

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