How to use bash array in a shell script

Bash arrays offer a powerful way to store and manipulate multiple values within a single variable. Understanding their operations empowers you to write efficient and dynamic scripts.

Bash Array

An array is a data structure that stores a collection of elements. Elements are accessed using indices, starting from 0. Arrays simplify data manipulation, enabling storage, retrieval, and modification of multiple values within a single variable. They are declared, populated, and operated upon using various Bash shell commands.

Let's look into the various operations with concise explanations and illustrative examples

Array Declaration

You can declare an array in Bash using the following syntax:

my_array=(element1 element2 element3)
Example:
fruits=("Apple" "Banana" "Orange")

Accessing Array Elements

You can access individual elements in an array using the index. The index starts at 0.

echo ${fruits[0]} # Outputs: Apple echo ${fruits[1]} # Outputs: Banana

Array Length

To get the length of an array, use the # symbol before the array name.

length=${#fruits[@]} echo "Number of elements in the array: $length" # Outputs: Number of elements in the array: 3

Adding Elements

You can add elements to an array using the += operator.

fruits+=("Grapes") echo ${fruits[@]} # Outputs: Apple Banana Orange Grapes

Removing Elements

Use the unset command to remove a specific element from an array.

unset fruits[1] # Removes Banana echo ${fruits[@]} # Outputs: Apple Orange Grapes

Iterating Through an Array

You can use a for loop to iterate through all elements in an array.

# Using a for loop for fruit in "${fruits[@]}"; do echo "Processing fruit: $fruit" done
# Using a while loop with index i=0 while [[ $i -lt ${#numbers[@]} ]]; do echo "Element at index $i: ${numbers[$i]}" ((i++)) done

Slicing Arrays

You can create a subarray by specifying a range of indices.

subarray=("${fruits[@]:1:2}") # Elements from index 1 to 2 (Banana and Orange) echo ${subarray[@]} # Outputs: Banana Orange

Searching for an Element

You can search for an element in an array using a loop.

search_element="Apple" for fruit in "${fruits[@]}"; do if [ "$fruit" == "$search_element" ]; then echo "Element found!" break fi done

Sorting an Array

Bash does not have built-in array sorting. You can use external tools like sort.

sorted_array=($(for i in "${fruits[@]}"; do echo $i; done | sort)) echo ${sorted_array[@]} # Outputs: Apple Grapes Orange

Substring Expansion

You can perform string operations on array elements:

# Extracting the first two characters of the first element in fruits echo "${fruits[0]:0:2}" # Output: ap # Converting all elements in colors to uppercase colors=("${colors[@]^^}") echo "${colors[@]}" # Output: RED GREEN BLUE

Array Operations

Bash provides powerful built-ins for manipulating arrays:

+= to append elements

numbers+=(6 7 8)

-= to remove elements

unset numbers[2] # Removes element at index 2

"${!array[@]}" to get all indices

indexes=("${!fruits[@]}") echo "Indices: ${indexes[@]}" # Output: 0 1 2

shopt -s lastarray for dynamic resizing

fruits+=("kiwi") # Automatically expands the array echo "${#fruits[@]}" # Output: 4

Conclusion

An array is a variable that holds a collection of values accessible by index. It simplifies data organization and manipulation, allowing users to store, retrieve, and modify multiple elements within a single variable using various shell commands.