Shell Arrays

Shell arrays can hold multiple values,Bash shell only support one-dimensional values(can not support multi-dimensional) .We don’t need to define array size during initialization (similar to PHP).The subscripts of array elements start from 0 which is similar to most programming languages.

We can use parentheses to indicate the arrays, and the array elements are separated by “space” symbol.

array_name=(value1 ... valueN)

For exmple:

#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

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

Accessing Array Values

After you have set any array variable, you access it as follows

${array_name[index]}

For example:

#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

my_array=(A B "C" D)

echo "the first element: ${my_array[0]}"
echo "the second element: ${my_array[1]}"
echo "the third element: ${my_array[2]}"
echo "the forth element: ${my_array[3]}"

Execute the script and the output as follows:

$ chmod +x test.sh 
$ ./test.sh
the first element: A
the second element: B
the third element: C
the forth element: D

Accessing All Array Values

We can use @ or * to access all array element values.For example:

#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

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

echo "array element values are: ${my_array[*]}"
echo "array element values are: ${my_array[@]}"

Execute the script and the output as follows:

$ chmod +x test.sh 
$ ./test.sh
array element values are: A B C D
array element values are: A B C D

Array Length

The method to obtain the length of the array is the same as the string’s, for example:

#!/bin/bash
# author:ylspirit
# url:www.linuxcommands.site

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

echo "the length of the array is: ${#my_array[*]}"
echo "the length of the array is: ${#my_array[@]}"

Execute the script and the output as follows:

$ chmod +x test.sh 
$ ./test.sh
the length of the array is: 4
the length of the array is: 4

Add a Comment

Your email address will not be published. Required fields are marked *