Lesson 10 | Using array variables |
Objective | Explain and apply indexed and associative arrays in Bash shell scripts. |
Declare and initialize:
# Compact initialization
flights=(1424 1425 492 1720)
# Explicit indices (0-based by default)
flights[0]=1424
flights[1]=1425
flights[2]=492
flights[3]=1720
Access elements and length:
echo "First flight: ${flights[0]}"
echo "Count: ${#flights[@]}" # number of elements
Append and insert:
flights+=("1880") # append to the end
flights[10]=9001 # creates a sparse array (indices 4..9 empty)
Delete elements:
unset 'flights[1]' # remove element at index 1
echo "${flights[@]}" # index 1 is now empty
Array slicing:
# Get 2 elements starting from index 1
subset=("${flights[@]:1:2}")
echo "${subset[@]}"
Iterate (indices and values):
# Values (preserves spaces/newlines in elements)
for f in "${flights[@]}"; do
echo "Flight: $f"
done
# Indices + values
for i in "${!flights[@]}"; do
echo "flights[$i] = ${flights[$i]}"
done
All elements vs single string:
# "${arr[@]}" → expands to N separate words (safe for spaces)
# "${arr[*]}" → expands to one word (joined by IFS)
printf '%s\n' "${flights[@]}" # preferred for robust loops
Great for lookups (Bash 4+):
declare -A airport_city=(
[SFO]="San Francisco"
[JFK]="New York"
[DFW]="Dallas–Fort Worth"
)
echo "${airport_city[JFK]}" # → New York
for k in "${!airport_city[@]}"; do
echo "$k → ${airport_city[$k]}"
done
# From a newline-separated file
mapfile -t flights < flights.txt # each line becomes one element (no trailing newlines)
# From a command safely (no word-splitting surprises)
mapfile -t users < <(getent passwd | cut -d: -f1)
Use name references (Bash 4.3+):
print_list() {
local -n ref="$1" # name reference to an array variable
for x in "${ref[@]}"; do printf '%s\n' "$x"; done
}
print_list flights
"${arr[@]}"
to preserve spaces/newlines in elements."${!arr[@]}"
.set -u
(nounset): Check existence with [[ ${arr[index]+x} ]]
before access.sh
, emulate with delimited strings or files, or switch to Bash.Array (indexed)
flights[0] = 1424
flights[1] = 1425
flights[2] = 492
flights[3] = 1720
Scalars (separate variables)
FLIGHT1 = 1424
FLIGHT2 = 1425
FLIGHT3 = 492
FLIGHT4 = 1720
echo "${flights[@]}" # prints each element as a separate word
printf '%s\n' "${flights[@]}" # one per line (safer for logs)
Arrays make Bash scripts clearer and safer whenever you manage lists or key–value pairs.
Prefer arrays over ad-hoc variable naming, iterate with "${!arr[@]}"
, and always quote expansions.
For strict POSIX sh
, plan alternatives or use Bash.