Using Arrays in Bash Scripts

Bash is a powerful and flexible shell scripting language found on most Unix-based systems. One of its underutilized features is support for arrays. This article explores how to create, read, and loop over arrays in Bash.


What Are Arrays in Bash?

An array is a variable that can hold multiple values, indexed by numbers. Unlike scalar variables, arrays can store lists, making them useful for managing grouped data.

Bash supports indexed arrays (with numerical indices) and, since version 4, associative arrays (with named indices). Here, we'll focus on indexed arrays.


Creating Arrays

Initialize with Values

fruits=('apple' 'banana' 'cherry')
  • Note: Values with spaces require quotes:
    names=("John Doe" "Jane Smith")

Add Elements Dynamically

fruits[3]='date'
fruits+=('elderberry')

Reading Arrays

Access Single Elements

echo "${fruits[0]}"   # Output: apple
echo "${fruits[2]}"   # Output: cherry

Access All Elements

echo "${fruits[@]}"         # apple banana cherry date elderberry
echo "${fruits[*]}"         # apple banana cherry date elderberry

Tip: Both @ and * serve a similar role, but they differ when quoted:

  • ${fruits[@]} treats each item as a separate string.
  • ${fruits[*]} joins all items into a single string if quoted.

Get Array Length

echo "${#fruits[@]}"   # Output: 5

Looping Over Arrays

Using for Loop

for fruit in "${fruits[@]}"; do
    echo "$fruit"
done

Looping with Indices

for index in "${!fruits[@]}"; do
    echo "fruits[$index] = ${fruits[$index]}"
done
  • ${!fruits[@]} expands to the list of all indices.

Modifying Arrays

Remove an Element

unset 'fruits[1]'          # Removes "banana"
  • Remaining elements’ indices stay the same; gaps are left in the indices.

Replace an Element

fruits[0]='apricot'

Practical Example

#!/bin/bash

servers=('server1' 'server2' 'server3')

for srv in "${servers[@]}"; do
    echo "Pinging $srv..."
    ping -c 1 "$srv" &> /dev/null

    if [[ $? -eq 0 ]]; then
        echo "$srv is reachable."
    else
        echo "$srv is NOT reachable."
    fi
done

Advanced: Associative Arrays (Bash 4+)

declare -A colors
colors[apple]='red'
colors[banana]='yellow'

echo "Apple is ${colors[apple]}"

Best Practices

  • Quote your variables: Always use quotes around "$var" or "${array[@]}" to handle spaces safely.
  • Check Bash version: Associative arrays require Bash ≥ 4.x.
  • Use ${!array[@]}: When you need all indices (e.g., for deletion or replacement).

Summary

Arrays in Bash greatly enhance your scripts’ flexibility. Use them to group related values, iterate over lists, and organize script logic more elegantly. With these building blocks, your Bash scripts can handle more complex tasks with ease.


Further Reading:


Did you find this guide helpful? Let us know your favorite array tricks in the comments!