Arrays & Associative Arrays
A normal variable holds one string. An array holds a list of strings, which is what you want for lists of files, servers or arguments, especially when items may contain spaces. Bash also has associative arrays (dictionaries/maps) that store values under string keys.
Indexed arrays
Create an array with parentheses, read one element with ${name[index]} (indexes start at 0):
servers=(web1 web2 "db primary")
echo "first: ${servers[0]}"
echo "third: ${servers[2]}"
echo "last: ${servers[-1]}"
echo "count: ${#servers[@]}"
echo "all: ${servers[@]}"first: web1
third: db primary
last: db primary
count: 3
all: web1 web2 db primary
| Syntax | Meaning |
|---|---|
arr=(a b c) |
Create |
${arr[i]} |
Element i (negative counts from the end) |
${arr[@]} |
All elements |
${#arr[@]} |
Number of elements |
${!arr[@]} |
All indexes |
${arr[@]:1:2} |
Slice: 2 elements starting at index 1 |
arr+=(d e) |
Append |
arr[5]=x |
Set one element |
unset 'arr[1]' |
Remove one element |
Note:
$serverswithout an index means${servers[0]}, the first element only. It's a common slip.
Looping over an array
Always use "${arr[@]}" (in double quotes) to loop. It expands to each element as a separate word, keeping spaces inside elements intact:
servers=(web1 web2 "db primary")
for s in "${servers[@]}"; do
echo "checking <$s>"
done
echo "--- unquoted (wrong):"
for s in ${servers[@]}; do echo "<$s>"; donechecking <web1>
checking <web2>
checking <db primary>
--- unquoted (wrong):
<web1>
<web2>
<db>
<primary>
To loop with positions, iterate over the indexes:
tasks=("write tests" "fix bug #12" "deploy")
for i in "${!tasks[@]}"; do
echo "$((i + 1)). ${tasks[i]}"
done1. write tests
2. fix bug #12
3. deploy
Changing arrays
queue=(alpha bravo charlie)
queue+=(delta)
queue[1]="BRAVO"
unset 'queue[2]'
echo "items: ${queue[*]}"
echo "count: ${#queue[@]}"
echo "indexes: ${!queue[*]}"
queue=("${queue[@]}")
echo "re-indexed: ${!queue[*]}"
echo "slice: ${queue[@]:1:2}"items: alpha BRAVO delta
count: 3
indexes: 0 1 3
re-indexed: 0 1 2
slice: BRAVO delta
unset leaves a gap: index 2 disappears but the others keep their numbers. Reassigning queue=("${queue[@]}") packs the array again. "${arr[*]}" joins all elements into one string separated by spaces (or by the first character of IFS).
Filling arrays from commands and files
mapfile (also called readarray) reads lines into an array, one element per line. It's the safe way to get a list from a file or command:
printf 'ada@example.com\nlinus@example.com\ngrace@example.com\n' > emails.txt
mapfile -t emails < emails.txt
echo "${#emails[@]} addresses, second: ${emails[1]}"
mapfile -t sorted < <(sort emails.txt)
echo "sorted first: ${sorted[0]}"
IFS=, read -r -a fields <<< "2026-03-15,sale,49.90"
echo "type=${fields[1]} amount=${fields[2]}"3 addresses, second: linus@example.com
sorted first: ada@example.com
type=sale amount=49.90
-t strips the newline from each line. < <(cmd) feeds a command's output (process substitution). read -a splits one line into an array, here on commas thanks to IFS=,.
Associative arrays
An associative array maps string keys to values. It must be declared with declare -A:
declare -A capital=([France]=Paris [Japan]=Tokyo)
capital[Kenya]=Nairobi
echo "Japan: ${capital[Japan]}"
echo "entries: ${#capital[@]}"
for country in $(printf '%s\n' "${!capital[@]}" | sort); do
echo "$country -> ${capital[$country]}"
done
[[ -v capital[Peru] ]] || echo "no entry for Peru"Japan: Tokyo
entries: 3
France -> Paris
Japan -> Tokyo
Kenya -> Nairobi
no entry for Peru
Keys come back in no particular order, so the loop sorts them first. [[ -v arr[key] ]] tests whether a key exists.
Counting with an associative array
A dictionary of counters is a very common pattern, for example counting HTTP status codes in a log:
cat > access.log <<'LOG'
GET /home 200
GET /cart 500
GET /home 200
POST /login 302
GET /admin 403
GET /home 200
LOG
declare -A hits
while read -r method path status; do
(( hits[$status]++ ))
done < access.log
for code in $(printf '%s\n' "${!hits[@]}" | sort -n); do
printf '%s: %d\n' "$code" "${hits[$code]}"
done200: 3
302: 1
403: 1
500: 1
while read (loops lesson) reads the file line by line, splitting each line into the three variables.
Arrays for command arguments
Building a command's arguments in an array is the clean way to handle optional flags and names with spaces:
printf 'sales up\ncosts down\n' > "q1 report.txt"
printf 'call the bank\n' > notes.txt
files=("q1 report.txt" notes.txt)
opts=(-l)
count_words=1
(( count_words )) && opts+=(-w)
echo "running: wc ${opts[*]} on ${#files[@]} files"
wc "${opts[@]}" "${files[@]}"running: wc -l -w on 2 files
2 4 q1 report.txt
1 3 notes.txt
3 7 total
Test yourself
a=(x y z). What does echo ${#a[@]} print?
- 1
- 3
- xyz
- 2
Which loop keeps elements with spaces intact?
- for x in ${a[@]}
- for x in "${a[@]}"
- for x in $a
- for x in "${a[*]}"
What must you do before using an associative array?
- Nothing
- declare -A name
- declare -a name
- export name