An indexed array is a data structure that stores a collection of elements accessed by numerical indices. These arrays are numerically indexed starting from zero by default. But it can be assigned values to specific indices, iterate over them, or perform various operations like adding or removing elements.
Let’s walk through the essential concepts along with Bash script examples to work with the Bash index array.
What is an Indexed Array in Bash?
An indexed array is a type of array that stores values (elements) and assigns an integer number as an index starting from 0 to N. Unlike some programming languages, Bash indexed array holds values of different data types (string, integer, etc).The indexed array in Bash has no upper limit on its size since it can store an indefinite number of elements depending on memory availability.
NOTE: To learn more about arrays in Bash, read the article “Bash Array”
Create an Indexed Array
The foremost step towards working with an Indexed array is to create it. Creation of an indexed array typically comprises naming the array, using parenthesis, and placing the values inside the parenthesis. To create an indexed array in Bash use the syntax: array_name=(value1 value2 value3…. valueN)
.
Look at the example below to create an indexed array in Bash:
#!/bin/bash
#Array creation
black=(tony jahan rubayet)
#echo to confirm array creation
echo "indexed array black is created with 3 elements"
In the above code, black=(tony jahan rubayet)
creates an indexed array black with 3 elements. The echo command in the last line prints a message to confirm the execution of the code to create the bash index array.
Using the “declare” Command
the declare command is used to declare variables and set their attributes. It’s particularly useful for explicitly defining variables and their behavior within a Bash script. To create an indexed array with the declare
command, use the flag -a
followed by the array name: declare -a <array_name>
.
Here is an example script that shows how to use declare -a to create an indexed array:
#!/bin/bash
#Array creation using declare -a command
declare -a arr1=(1 2 three 4)
#echo to confirm array creation
echo "indexed array arr1 is created with 3 elements"
In the script, the declare -a
command creates an array arr1 with explicit declaration and the echo
command confirms the creation printing a message on the screen.
declare -a
command has created an indexed array, and echoing the message indexed array arr1 is created with declare -a confirms it.
NOTE: you can create an empty indexed array using declare -a array_name
or array_name=()
command and assign values later.
View the Length of an Indexed Array
The length expression ${#array[@]} syntax returns the length (total number of elements) of an index array and to print the length of an indexed array, use the syntax: echo ${#array[@]}
Here’s how to print the length of an indexed array in Bash using the syntax echo ${#array[@]}
:
#!/bin/bash
#array declaration
keepers=(gilly buzz mushy)
#printing the array
echo ${keepers[*]}
#print the length
echo "the length: ${#keepers[*]}"
In the bash script above, the syntax ${#keepers[*]}
returns the length of the array (which is 3) keepers, and the echo command displays on the screen.
echo ${#keepers[*]}
prints the length (3) of the array named keepers.
Print an Indexed Array
The length expressions ${array[@]} or ${array[*]} prints all the elements located at specified indices using the echo command.
Here’s how to print an indexed array called artcell in Bash employing the syntax echo ${artcell[@]}
and echo ${artcell[*]}
:
#!/bin/bash
#Array creation
artcell=(lincoin ershad sazu sezan)
#printing array length to the terminal using both expressions
echo "the array elements printed using \${artcell[@]}: ${artcell[@]}"
echo # for adding extra spaces between the outputs
echo "the array elements printed using \${artcell[*]}: ${artcell[*]}"
In the above code, the expressions ${artcell[@]}
and ${artcell[*]}
take the array items and print them to the screen using the echo command.
echo ${artcell[@]}
and echo ${artcell[*]}
Using the “printf” Command
The printf command formats and prints text or variables to the standard output. However, to print, the elements of an array in Bash, use the syntax: printf "%s\n" "${array[@]}"
.
Here is an example of how to use the above syntax printf "%s\n" "${array[@]}"
in a Bash script:
#!/bin/bash
#create an array with 3 elements
fruits=("apple" "orange" "banana")
#print the array using printf command
printf "%s\n" "${fruits[@]}"
In the above code, the printf
command prints the items of the array named fruits using the expression ${fruits[@]}
. The \n
is a newline character telling printf to display elements with newlines and %s
accepts the elements as an argument.
Print Specific Elements of an Indexed Array
To print access only the specific elements of an indexed array in Bash, use the index notation syntax echo ${array[index]}
.
Here’s an example to access indexed array elements using echo ${array[index]}
:
#!/bin/bash
#array declaration
finders=(sherlock byomkesh masud)
#printing the array
echo "all items: ${finders[@]}"
echo
#printing only the 1st element using finders[0]
echo "1st item: ${finders[0]}"
In this script, the command echo ${finders[0]}
prints the 1st element of the array (sherlock) finders consisting of 3 elements (sherlock byomkesh masud). The previous line prints the entire array using echo ${finders[@]}
to display the differences and verify the process.
Print Elements of an Index Array Using the “for” Loop
The for loop in Bash prints the entire indexed array with a new line. It’s a powerful tool that iteratively accesses each array element and prints them with the echo
or the printf
command
To print an indexed array in Bash using for
loops, see the following script:
#!/bin/bash
#Declaring an indexed array and assigning it with values
drinko=(lichie pine orange)
#looping through the elements to print
for flavor in ${drinko[@]}
do
echo $flavor
done
First, the complete looping expression for elements in ${drinko[@]}
iterates through the drinko array until it covers the entire array length (which is 3) and prints the items into the terminal iteratively on new lines using echo $flavor
.
However, loop can print elements from a specific portion of the array. To access array elements from indices S to E exclusive using the loop syntax for ((i = S; i < E; i++)):
Again, to access the last N elements from an array, use the syntax for ((i=length-N; i < length; i++)):
Here is a script to access the last 2 elements of an array:
#!/bin/bash
#array declaration with elements
greenDay=("21Guns" "holiday" "enemy" "basketCase" "forgotten")
# Get the length of the array
length=${#greenDay[@]}
#print the entire array
echo "entire array: ${greenDay[@]}"
echo
echo "last 2:"
# Print the last 2 elements using a for loop
for ((i = length - 2; i < length; i++)); do
echo "${greenDay[i]}"
done
The above script creates an indexed array greenDay with 5 elements. The loop for ((i = length - 2; i < length; i++))
prints the last 2 elements of that array starting from the condition, “i = length – 2” (which is the second-to-last element up to the end of the array), using the command echo ${greenDay[i]}
.
for
loop
Printing the Indices of an Indexed Array
To print the index values of the array elements, use the usual length expression ${array[@]} with “!” like this syntax as a prefix along with the echo command like this syntax: echo ${!array[@]}
. The exclamation mark (!), in the expression ${!array[@]}, tells the expression to expand the indices of the array rather than the individual elements. Here’s an example:
#!/bin/bash
#array declaration
coach=(donald rhodes whatmore)
#print elements
echo "elements are: ${coach[@]}"
echo
#print the index
echo "the indices are: ${!coach[@]}"
In the bash script above, the length expression ${!coach[@]}
expands to all the indices of the array coach and the echo
command displays the index values 0 1 2 on the screen.
The output will look like this: The above script outputs the index values (0 1 2) of the array coach with 3 elements (donald rhodes whatmore).
Appending Elements to an Index Array
To append means to add a new element at the end of an array. The +=
operator appends a new element to the end of that array with the syntax array+=(element to append)
.
Here’s an example script to append elements to an indexed array using array+=(element to append)
:
#!/bin/bash
#array declaration with elements
example_array=(EEE CE)
#print array before append
echo "before: ${example_array[@]}"
#append element
example_array+=(ME)
#print array after append
echo "after appending: ${example_array[@]}"
example_array+=(ME)
to append a new element ME to the example_array with 2 elements. The final echo
command prints the array with 3 elements (EEE CE ME).
example_array+=(ME)
expression adds a new element ME to the array which is evident after printing the array in the last line.
NOTE: To append an array, arr1, to another array, arr2, use arr2+=(${arr1[@]})
Updating Elements of an Indexed Array
To update the content of an array element, assign a new value by using its index value using the syntax: array[index]= new value
to assign. Here’s an example:
#!/bin/bash
#Declaring the array
declare -a example_array=("welcome" "to" "linuxsimply")
#Printing all the elements of the Array
echo "before updation:${example_array[@]}"
#Updating the Array Element
example_array[2]=softeko
#Printing all the elements of the Array
echo "after updation:${example_array[@]}"
Here, the example_array[2]=softeko
expression updates the content of index 2 (3rd position) from linuxsimply to softeko. The echo “after updation:${example_array[@]}”
command prints the array with the updated contents.
example_array[2]=softeko
replaces the item linuxsimply at index 2 of the example_array with softeko.
Slicing an Indexed Array
To slice an indexed array in Bash from a specific starting index to an ending index, use the syntax: ${array_name[@ or *]:Start:Count}
.
The slicing expression ${array_name[@ or *]:Start:Count}
slices an indexed array beginning from the index Start (0,1,2…) and extracts the number of elements specified by Count. For example, the command echo ${array_name[@ or *]:2:5}
prints 5 elements starting from index 2.
To print 5 elements from an array of 8 elements starting from index 2, you can use echo ${array_name[@ or *]:2:5}
. Here’s an example:
#!/bin/bash
#create an indexed array
juice=("apple" "banana" "cherry" "date" "grape" "peach" "dragon" "kiwi")
#print entire array
echo ${juice[@]}
#print 5 elements starting from index 2
echo ${juice[@]:2:5}
Here, the expression ${juice[@]:2:5}
begins from index 2 to access 5 elements inclusive. Finally, the echo
command prints the items to the prompt.
echo ${juice[@]:2:5}
command prints 5 elements (cherry date grape peach dragon) out of 8 elements starting from the 3rd element.
Removing Elements of an Indexed Array
To delete an array element, use the unset command followed by the index value like the syntactical format: unset example_array[index]
Here’s an example to show how to remove an element from an indexed array using the unset array_name[index]
:
#!/bin/bash
# the array
brands=(adidas puma nike)
#print array
echo "before removal: ${brands[@]}"
# Deleting nike from the array
unset brands[2]
#printing the array after removal of the element nike
echo "after removal: ${brands[@]}"
In the script, the unset
command followed by the syntax (brands[2])
removes the third element nike. After that, the echo
command prints the array and shows that the unset command has removed the array element.
unset brands[2]
has removed the item nike from the brands array.
Remove All the Elements Using ‘()’
To keep an indexed array empty by removing all the items, simply recreate the array using the syntax: array_name=()
:
#!/bin/bash
# create an array with elements
num=(1 2 3)
#print the array
echo "the current array: ${num[@]}"
echo
#recreate the array
num=()
#print the array after recreation
echo "elements after recreating: ${num[@]}"
Here, the expression num=()
recreates the already extant array called num with 3 elements 1 2 3. In turn, it also removes all the items and only the empty array remains which is evident in the last line where the echo
command tries to print the elements and gets nothing.
num=()
Delete All the Elements Using ‘unset’ Command
The unset command in Bash is used to remove variables and functions. So, it can be used to delete an entire indexed array. It requires only the use of the syntax: unset <array name>
.
The below script shows an example of how to use unset to delete all the elements of an indexed array:
#!/bin/bash
# create an array
bat=(man teen child)
#print array before deletion
echo "before deletion:${bat[@]}"
#delete the array with unset
unset bat
#print array again
echo "after deletion:${bat[@]}"
In, the above script the line unset bat
deletes the array named bat. Printing the array after running the unset bat
displays no elements on the screen that verify array element removal.
echo ${bat[@]}
. This empty result is the exemplar that the array bat is not extant anymore.
Find the Index of a Specific Element
To find the index of a specific element of an indexed array, use the Bash for loop to iterate over the array and match the condition if the current element equals the specified element. If yes, the loop stores the index value and breaks to find the value of the first occurrence. Otherwise, the loop covers the entire array and tracks the index of the last occurrence of that element.
Find First Occurrence
To find the index of the first occurrence of the specified item using the for
loop, see the script below:
#!/bin/bash
#create array
arr=("banana" "mango" "cherry" "mango" "grape")
#Specified element
element="mango"
index=-1 # initializing the flag to -1
#loop to track element
for i in "${!arr[@]}";
do
if [[ "${arr[$i]}" = "${element}" ]];
then
index=$i
break
fi
done
#printing the index if found
if [ $index -gt -1 ];
then
echo "first occurence of $element in Array is at index : $index"
else
echo "Element is not in Array."
fi
The above script finds the 1st occurred index of the element “mango”. Here, the for i in "${!arr[@]}
loop with break
statement finds the match for “mango” and after finding the element, it sets the value of the index variable to the current value of i and immediately breaks the loop.
for
loop returns the index of the element “mango” as 1 which is the position of its 1st occurrence.
Find Last Occurrence
To find the index of the last occurrence of the specified element, use the same condition but without the break
statement:
#!/bin/bash
arr=("apple" "banana" "mango" "cherry" "mango" "grape")
element="mango"
index=-1
for i in "${!arr[@]}";
do
if [[ "${arr[$i]}" = "${element}" ]];
then
index=$i
fi
done
if [ $index -gt -1 ];
then
echo "Last occurence of $element in Array is at index : $index"
else
echo "Element is not in Array."
fi
Script output to print the last occurrence index value of the specified element “mango”
Reordering an Index Array
Reordering an array typically refers to rearranging the elements within the array according to a specific order or criteria. This can involve sorting the elements based on numerical or alphabetical order, shuffling them randomly, or arranging them in a custom-defined sequence.
Here’s an example script for reordering an indexed array in Bash:
#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")
order=(4 2 0 3 1)
#print array
echo ${items[@]}
echo
#print elements in reorder
for i in "${order[@]}"
do
echo ${items[$i]}
done
In the above example, the order array holds the new order of elements (4 2 0 3 1). Then, the for loop for i in "${order[@]}"
iterates the order array to use each value as an index and uses this index to print the array items in a reordered pattern.
Conclusion
Indexed arrays in Bash are versatile and commonly used for storing and manipulating collections of items, offering flexibility in managing data within scripts. Hope this article guides you through the ins and outs of the indexed array in Bash with practical examples. Hope it elevates your data-handling capability for efficient script development. Still, if you face any difficulty, feel free to share in the comment section. Happy scripting!
Frequently Asked Questions
What is the difference between array length and array size in Bash?
Array length refers to the number of elements present in the array in Bash. You can get the array length by using echo ${#array[@]}
command. Contrarily, the array size is the allotted or occupied memory by the array. In Bash, arrays automatically resize so there’s no pre-defined size in Bash array.
How to echo a Bash Array?
To echo a Bash array, use the length expression command echo ${array[@]}
. For example, to echo an array nums, the command is: echo ${nums[@]}
. You can also use length expression ${nums[*]} prefixing with the echo command.
Can I print the index value of an array in Bash?
Yes, you can use the syntax echo ${!array_name[@]}
to print the indices of an indexed array in Bash. For instance, to print the indices of the nums array with 3 elements use: echo ${!nums[@]}
. The output will be 0 1 2.
How to delete an indexed array in Bash?
Use the unset
command followed by the array name to delete that array. For instance, the unset example_array
will delete the array called example_array.
How can I access the last element of an Indexed array?
You can use negative indexing -1
with the echo
command to access the last element of an indexed Bash array. For example, the command echo ${items[-1]}
will print the last element of the items array.
Can I use the “printf” command in the for loop to print an indexed array?
Yes, you can use the printf
command within the for loop to print an indexed array like the following:
myArray=("element1" "element2" "element3")
for element in "${myArray[@]}"; do
printf "%s " "$element"
done
How to print the length of an indexed array in Bash?
The length of an indexed array means the number of elements stored in the array. To print the length of an indexed array, use the command echo ${#array[@]}
Related Articles
- Declare Array in Bash [Create, Initialize]
- How to Read into Bash Array [3 Methods]
- Bash Associative Arrays [Explained]
- Bash Array of Arrays [Explained]
- Elements of Bash Array
<< Go Back to Bash Array | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners