English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Shell Arrays

Arrays can store multiple values. Bash Shell only supports one-dimensional arrays (does not support multi-dimensional arrays), and does not need to define the size of the array when initializing (similar to PHP).

Similar to most programming languages, the index of array elements starts from 0.

Shell arrays are represented by parentheses, and elements are separated by "space" symbols, with the syntax format as follows:

array_name=(value1 value2 ... valuen)

Online Example

#!/bin/bash
# author:Basic Tutorial Website
# url:www.oldtoolbag.com
my_array=(A B "C" D)

We can also use an index to define an array:

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

Read an array

The general format for reading the value of an array element is:

${array_name[index]}

Online Example

#!/bin/bash
# author:Basic Tutorial Website
# url:www.oldtoolbag.com
my_array=(A B "C" D)
echo "The first element is: ${my_array[0]}"
echo "The second element is: ${my_array[1]"
echo "The third element is: ${my_array[2]"
echo "The fourth element is: ${my_array[3]"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
The first element is: A
The second element is: B
The third element is: C
The fourth element is: D

Get all elements of the array

Use @ or * You can get all elements of the array, for example:

#!/bin/bash
# author:Basic Tutorial Website
# url:www.oldtoolbag.com
my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D
echo "The elements of the array are: ${my_array[*]"
echo "The elements of the array are: ${my_array[@]}"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
The elements of the array are: A B C D
The elements of the array are: A B C D

Get the length of an array

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

#!/bin/bash
# author:Basic Tutorial Website
# url:www.oldtoolbag.com
my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D
echo "The number of array elements is: ${#my_array[*]"
echo "The number of array elements is: ${#my_array[@]}"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
The number of array elements is: 4
The number of array elements is: 4