Multiple values can be stored in an array. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and the subscripts of array elements start from 0.
Shell arrays are represented by brackets, and elements are separated by "space" symbols. The syntax is as follows:
array_name=(value1 ... valuen)
read array
# vi test.sh
#!/bin/bash
array1=(a b c d)
echo "First element: ${array1[0]}"
echo "Second element: ${array1[1]}"
echo "The third element: ${array1[2]}"
echo "Fourth element: ${array1[3]}"
output:
# sh test.sh
first element: a
second element: b
third element: c
Fourth element: d
Get all elements in an array:
# vi test.sh
#!/bin/bash
array1[0]=a
array1[1]=b
array1[2]=c
array1[3]=d
echo "Element of array: ${array1[*]}"
echo "Element of array: ${array1[@]}"
output:
# sh test.sh
Elements of the array: abcd
Elements of the array: abcd
Get the number of elements in an array:
# vi test.sh
#!/bin/bash
array1[0]=a
array1[1]=b
array1[2]=c
array1[3]=d
echo "Number of elements in the array: ${#array1[*]}"
echo "Number of elements in array: ${#array1[@]}"
output:
# sh test.sh
Number of elements in the array: 4
Number of elements in the array: 4