Table of Contents
In this tutorial we’ll learn about Arrays in Shell Scripts, how we can create, access, and manipulate arrays in your scripts.
Arrays are powerful tools in shell scripting, allowing you to store and manage multiple values under a single name.
Declaring Arrays in shell scripts
There are two ways to declare arrays in shell scripts:
- Using parentheses:
fruits=(apple banana orange)
numbers=(1 2 3 4 5)
- Using the
declare
command:
declare -a names=("Alice" "Bob" "Charlie")
declare -i ages=(25 30 40) # Declares as integers
The -a
flag with declare
specifies an associative array, while the -i
flag declares an integer array. Associative arrays allow you to use custom keys instead of numerical indices. We’ll cover them later.
Accessing Elements in shell scripts
Array elements are accessed using numerical indices starting from 0.
first_fruit=${fruits[0]} # Accesses the first element (apple)
second_number=${numbers[1]} # Accesses the second element (2)
Iterating through Arrays in shell scripts
Looping through each element is essential for processing array data.exclamation Here are two common methods:
1. For loop:
for fruit in "${fruits[@]}"; do
echo "I like $fruit!"
done
This iterates through all elements and assigns each to the loop variable fruit
. The @
symbol expands the entire array.
2. While loop:
index=0
while [ $index -lt ${#fruits[@]} ]; do
echo "The ${index}th fruit is ${fruits[$index]}"
index=$((index+1))
done
This uses a counter variable index
to access elements one by one. ${#fruits[@]}
gives the total number of elements.
Modifying Arrays in shell scripts
You can modify existing elements or add new ones:
- Change an element:
fruits[2]="mango" # Replaces the third element with "mango"
- Append an element:
fruits+=("grapes") # Adds "grapes" to the end of the array
Associative Arrays (Key-Value Pairs):
These use custom keys instead of indices:
declare -A contacts
contacts["Alice"]="alice@example.com"
contacts["Bob"]="bob@example.com"
echo "Alice's email: ${contacts["Alice"]}"
Access elements using their assigned keys within square brackets.
Remember:
- Arrays are zero-indexed, so the first element starts at 0.
- Use
@
symbol to expand all elements in loops or expressions. - Choose associative arrays when using custom keys, otherwise stick to numerical indices.