BASH Programming

How to Use Index Arrays in Bash

Bash provides support for indexed arrays, which are essentially lists of elements that can be accessed using their index number. Indexed arrays are particularly useful when you want to store and manipulate many related values, further read this article to learn how to use index arrays.

What are Index Arrays

Indexed arrays are a collection of elements in bash that can be accessed using an index or a key. These arrays can be used to store and retrieve data in a specific order, making it easier to manage large amounts of data. The syntax for declaring an indexed array in bash is as follows:

<array_name> =( element1 element2 element3 ... )

Here, array_name is the name of the array, and element1, element2, element3, and so on are the values to be stored in the array. The values are separated by whitespace and note that you can also use the declare command to create an array.

How to Use Indexed Arrays in Bash

To create an index array in bash, you simply need to declare a variable and assign it values enclosed in parentheses and separated by spaces. Here are few examples that demonstrates how to use indexed arrays in bash:

Reordering a List in Bash

If you have a list of items in a certain order and you want to reorder them in a different way. You can use an index array to create a new order for the items, as follows:

#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")
order=(4 2 0 3 1)
for i in "${order[@]}"
do
   echo ${items[$i]}
done

In this example, we create an array called items with five elements. We also create an index array called order, which specifies a new order for the items. We then loop through the order array and use each value as an index to retrieve the corresponding item from the items array and print it out.

Filtering a List in Bash

If you have a list of items and you want to filter out certain items based on a condition. You can use an index array to keep track of the indices of the items that meet the condition, as follows:

#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")
indices=()

for i in "${!items[@]}"
do
   if [[ ${items[$i]} == *"r"* ]]
   then
      indices+=($i)
   fi
done

for i in "${indices[@]}"
do
   echo ${items[$i]}
done

In this example, we create an array called items with five elements. We also create an empty index array called indices. We then loop through the items array and check if each item contains the letter “r”. If it does, we add its index to the indices array. Finally, we loop through the indices array and use each value as an index to retrieve the corresponding item from the items array and print it out.

Counting Occurrences in Bash

If you have a list of items and you want to count the number of occurrences of each item, you can use an index array to keep track of the counts and here is an example for demonstration:

#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")
counts=()

for i in "${!items[@]}"
do
   if [[ ! "${counts[@]}" =~ "${items[$i]}" ]]
   then
      counts+=("${items[$i]} 1")
   else
      index=$(echo "${counts[@]}" | tr ' ' '\n' | grep -n "^${items[$i]}" | cu)
      count=$(echo "${counts[$index-1]}" | cut -d' ' -f2)
      counts[$index-1]="${items[$i]} $((count+1))"
   fi
done

for count in "${counts[@]}"
do
   echo $count
done

It first initializes an array called “items” with a list of strings. Then it declares an empty array called “counts”. A for loop is created to iterate for each item in the “items” array and for each item it checks if it already exists in the “counts” array.

If it does not exist, it adds the item and the count of 1 to the “counts” array. If it does exist, it increments the count of that item in the “counts” array. Finally, to print out each item and its corresponding count another for loop is used. The output of this code will print out the count of each item in the “items” array, with duplicates being counted separately.

Updating a List in Bash

If you have a list of items and you want to add or delete items from it then you can use an index array for it and here is an example for demonstration:

#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")

# Adding a new element to the indexed array at index 2
items[6]="orange"
# Deleting the element at index 2 from the indexed array
unset items[2]

# Printing the updated array
echo "${items[@]}"

In the script an indexed array “items” is defined with five initial elements. To add a new element, the value is simply assigned to the desired index using the syntax array[index]=value. In this script, “orange” is added to index 6 of the array. To delete an element, we use the unset command followed by the index of the element we want to remove. In this case, the element at index 2 (“Strawberry”) is deleted. The updated array is then printed using the syntax “${array[@]}”, which expands the entire array.

Conclusion

The indexed arrays are a handy structure of bash that allow you to store and manipulate multiple values using a single variable. By understanding the syntax and usage of indexed arrays, you can write more efficient and effective bash scripts.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.