Arrays in Bash
An array is a variable that holds multiple values under one name. Instead of creating ten separate variables for ten values, store all of them in a single array and access each one by its position number.
What Is an Array?
┌──────────────────────────────────────────────────────┐
│ Without Array: │
│ city1="Delhi" │
│ city2="Mumbai" │
│ city3="Pune" │
│ │
│ With Array: │
│ cities=("Delhi" "Mumbai" "Pune") │
│ │
│ Index: 0 1 2 │
└──────────────────────────────────────────────────────┘
Declaring an Array
#!/bin/bash
fruits=("Apple" "Banana" "Mango" "Orange")
An array can also be declared explicitly:
declare -a colors colors[0]="Red" colors[1]="Green" colors[2]="Blue"
Accessing Array Elements
Access an individual element using its index number inside curly braces. Array indices start at 0.
#!/bin/bash
fruits=("Apple" "Banana" "Mango" "Orange")
echo ${fruits[0]} # First element
echo ${fruits[2]} # Third element
Output:
Apple Mango
Accessing All Elements
#!/bin/bash
fruits=("Apple" "Banana" "Mango" "Orange")
echo ${fruits[@]} # All elements
echo ${fruits[*]} # All elements (alternate syntax)
Output:
Apple Banana Mango Orange Apple Banana Mango Orange
Array Length
#!/bin/bash
fruits=("Apple" "Banana" "Mango" "Orange")
echo "Total fruits: ${#fruits[@]}"
Output:
Total fruits: 4
Modifying Array Elements
#!/bin/bash
fruits=("Apple" "Banana" "Mango")
fruits[1]="Grapes" # Replace Banana with Grapes
echo ${fruits[@]}
Output:
Apple Grapes Mango
Adding Elements to an Array
#!/bin/bash
fruits=("Apple" "Banana")
fruits+=("Mango" "Orange")
echo ${fruits[@]}
Output:
Apple Banana Mango Orange
Removing an Element
#!/bin/bash
fruits=("Apple" "Banana" "Mango" "Orange")
unset fruits[2] # Remove Mango (index 2)
echo ${fruits[@]}
Output:
Apple Banana Orange
Looping Over an Array
Using for Loop
#!/bin/bash
cities=("Delhi" "Mumbai" "Chennai" "Kolkata")
for city in "${cities[@]}"
do
echo "City: $city"
done
Output:
City: Delhi City: Mumbai City: Chennai City: Kolkata
Loop with Index
#!/bin/bash
fruits=("Apple" "Banana" "Mango")
for i in "${!fruits[@]}"
do
echo "Index $i: ${fruits[$i]}"
done
Output:
Index 0: Apple Index 1: Banana Index 2: Mango
Array Slicing
Extract a portion of an array using ${array[@]:start:count}.
#!/bin/bash
nums=(10 20 30 40 50 60)
echo ${nums[@]:2:3} # Start at index 2, take 3 items
Output:
30 40 50
Associative Arrays (Key-Value Pairs)
Associative arrays use text keys instead of numbers. This feature requires Bash version 4 or higher.
#!/bin/bash
declare -A student
student["name"]="Ravi"
student["age"]="22"
student["city"]="Hyderabad"
echo "Name: ${student["name"]}"
echo "Age: ${student["age"]}"
echo "City: ${student["city"]}"
Output:
Name: Ravi Age: 22 City: Hyderabad
Loop Over Associative Array
#!/bin/bash
declare -A capital
capital["India"]="New Delhi"
capital["Japan"]="Tokyo"
capital["France"]="Paris"
for country in "${!capital[@]}"
do
echo "$country → ${capital[$country]}"
done
Output:
India → New Delhi Japan → Tokyo France → Paris
Indexed vs Associative Array Comparison
| Feature | Indexed Array | Associative Array |
|---|---|---|
| Key type | Number (0, 1, 2…) | String ("name", "city"…) |
| Declaration | arr=() or declare -a | declare -A |
| Bash version | All versions | Bash 4+ |
| Access | ${arr[0]} | ${arr["key"]} |
Practical Example – Student Score Report
#!/bin/bash
declare -A scores
scores["Alice"]=88
scores["Bob"]=72
scores["Carol"]=95
for student in "${!scores[@]}"
do
if [ ${scores[$student]} -ge 90 ]; then
grade="A"
elif [ ${scores[$student]} -ge 75 ]; then
grade="B"
else
grade="C"
fi
printf "%-10s Score: %d Grade: %s\n" "$student" "${scores[$student]}" "$grade"
done
Output:
Alice Score: 88 Grade: B Bob Score: 72 Grade: C Carol Score: 95 Grade: A
Key Takeaways
- Arrays hold multiple values under one name using numeric indices starting at 0.
- Use
${array[@]}to access all elements and${#array[@]}for the count. - Use
+=to append new elements andunsetto remove one. - Loop over arrays using
for item in "${array[@]}". - Associative arrays use string keys and require
declare -A.
