Accessing Array Elements
Once you have declared a Shell array, you can access its elements in various ways. Let's explore the different techniques for accessing array elements.
Accessing Individual Elements
To access a specific element in an array, you can use the array index enclosed in curly braces {}
after the array name.
my_array=(apple banana cherry)
## Access individual elements
echo ${my_array[0]} ## Output: apple
echo ${my_array[1]} ## Output: banana
echo ${my_array[2]} ## Output: cherry
Accessing All Elements
You can access all elements in an array by using the @
or *
symbol within the curly braces.
my_array=(apple banana cherry)
## Access all elements
echo ${my_array[@]} ## Output: apple banana cherry
echo ${my_array[*]} ## Output: apple banana cherry
Accessing a Range of Elements
To access a range of elements, you can use the array index with a colon :
to specify the start and end indices.
my_array=(apple banana cherry date fig)
## Access a range of elements
echo ${my_array[@]:1:3} ## Output: banana cherry date
Accessing the Length of an Array
You can determine the length of an array by using the #
symbol before the array name.
my_array=(apple banana cherry)
## Get the length of the array
echo ${#my_array[@]} ## Output: 3
By understanding these techniques for accessing array elements, you can effectively manipulate and work with arrays in your Shell scripts.