Iterating Over Associative Arrays
An associative array (lesson 102) is useful for looking up one value by its key, but many tasks need every entry: printing a report, adding up totals, finding the entries that match a condition, or writing the data back to a file. This lesson shows how to walk through the keys and values of an associative array, why the order of the entries is not the order they were added, and how to produce sorted output when order matters.
All examples in this lesson start from this array of stock counts:
declare -A stock=([apples]=12 [bananas]=0 [cherries]=150 ["dragon fruit"]=7)
The Two Expansions
Associative arrays use the same expansion syntax as indexed arrays, with one change in meaning:
| Expansion | Indexed array | Associative array |
|---|---|---|
"${arr[@]}" | all values | all values |
"${!arr[@]}" | all indexes (numbers) | all keys (strings) |
${#arr[@]} | number of elements | number of keys |
The keys are the important one. With them, every value can be read with ${arr[$key]}, so a loop over keys gives access to both halves of each entry.
Looping Over Keys
for k in "${!stock[@]}"; do
echo "key: [$k]"
done
key: [cherries]
key: [apples]
key: [dragon fruit]
key: [bananas]
Each pass sets k to one key, exactly as stored, including the space in dragon fruit. The quotes around "${!stock[@]}" are required: keys are arbitrary strings, and without quotes Bash splits them on whitespace and treats glob characters as patterns:
for k in ${!stock[@]}; do echo "[$k]"; done
[cherries]
[apples]
[dragon]
[fruit]
[bananas]
dragon fruit became two passes, and neither dragon nor fruit is a key in the array.
Looping Over Keys and Values Together
Inside the key loop, the value is one lookup away:
for k in "${!stock[@]}"; do
echo "$k => ${stock[$k]}"
done
cherries => 150
apples => 12
dragon fruit => 7
bananas => 0
This is the form to reach for by default. It works for printing, filtering, totals and modifying values, and the key is never lost.
Looping Over Values Only
When the keys are not needed, "${arr[@]}" gives the values directly:
for v in "${stock[@]}"; do
echo "value: $v"
done
value: 150
value: 12
value: 7
value: 0
Here the values came out in the same order as the keys in the previous loop, because both expansions walk the same internal table. Even so, a value loop has no way to say which key a value belongs to, and a loop over keys with a lookup is clearer than relying on two separate lists staying in step.
A value loop is the natural fit for totals:
total=0
for v in "${stock[@]}"; do (( total += v )); done
echo "total: $total"
total: 169
The Order of Entries
The loops above printed cherries, apples, dragon fruit, bananas, which is neither alphabetical nor the order of the assignment. Bash stores associative arrays in a hash table (lesson 102), and the expansions list the entries in the table's internal order. Another small example makes this clear:
declare -A o
o[zeta]=1; o[alpha]=2; o[mid]=3; o[beta]=4
echo "${!o[@]}"
alpha mid beta zeta
The order depends on the keys and on Bash's hashing, and it can differ between Bash versions. A script must never depend on it. When the output order matters, sort the keys first.
Sorting the Keys
Bash has no built-in sort, but the sort command works on lines of text. The usual pattern prints each key on its own line with printf '%s\n' (lesson 100), pipes that into sort, and reads the sorted lines back into an indexed array with mapfile and process substitution (lesson 98):
mapfile -t keys < <(printf '%s\n' "${!stock[@]}" | sort)
for k in "${keys[@]}"; do
printf '%-14s %5d\n' "$k" "${stock[$k]}"
done
apples 12
bananas 0
cherries 150
dragon fruit 7
How it works:
printf '%s\n' "${!stock[@]}"repeats its format for every key, producing one key per line.sortorders the lines.sort -rwould reverse them, andsort -fwould ignore case.< <( ... )feeds the sorted lines tomapfilein the current shell, so thekeysarray still exists after the line runs. Piping intomapfileinstead would run it in a subshell and lose the result (lesson 98).mapfile -tstrips the newline from each line, so every element ofkeysis exactly one key, spaces included.- The loop then walks
keysin order and looks up each value.%-14sleft-aligns the key in 14 columns and%5dright-aligns the number in 5 (lesson 30).
This method handles keys with spaces. It does not handle keys that contain a newline, since each key must fit on one line; such keys are rare, but if they are possible, the data should be kept in another form.
Sorting by Value
To order entries by their values, print each value and key together, sort on the value, and split the lines again. A tab between the two fields keeps keys with spaces intact:
for k in "${!stock[@]}"; do
printf '%s\t%s\n' "${stock[$k]}" "$k"
done | sort -t $'\t' -k1,1nr |
while IFS=$'\t' read -r qty name; do
printf '%-14s %5d\n' "$name" "$qty"
done
cherries 150
apples 12
dragon fruit 7
bananas 0
The sort options:
-t $'\t'sets the field separator to a tab (lesson 47 covers$'...').-k1,1sorts on the first field only.ncompares the field as a number, so 150 comes after 12 rather than before it.rreverses the order, giving the largest values first.
The final while loop runs at the end of a pipe, so any variables it sets are lost when it finishes (lesson 61). That is fine for printing. If the sorted result must be kept, read it with mapfile from process substitution as in the previous section.
Filtering Entries
A condition inside the key loop selects the entries to act on:
for k in "${!stock[@]}"; do
(( stock[$k] == 0 )) && echo "out of stock: $k"
done
out of stock: bananas
Inside (( )), stock[$k] reads the value as a number without needing ${ }.
Changing Values During a Loop
Assigning to arr[$k] inside a key loop updates the array in place. This raises every price by 10 percent with integer arithmetic:
declare -A price=([tea]=40 [coffee]=60)
for k in "${!price[@]}"; do
price[$k]=$(( price[$k] * 110 / 100 ))
done
declare -p price
declare -A price=([tea]="44" [coffee]="66" )
Changing the value of a key that is already in the list is always safe, because the loop's list of keys was fixed before the first pass.
Removing Entries During a Loop
For the same reason, removing keys inside the loop works as expected. Each key in the list is visited once; a removed entry is simply gone from the array afterward:
declare -A d=([a]=1 [b]=0 [c]=3 [e]=0)
for k in "${!d[@]}"; do
(( d[$k] == 0 )) && unset 'd[$k]'
done
declare -p d
declare -A d=([c]="3" [a]="1" )
The single quotes in unset 'd[$k]' stop the brackets from being treated as a glob pattern, and Bash still expands $k when it looks up the element (lesson 102).
Adding Entries During a Loop
New keys added inside the loop are not visited by the same loop, because "${!g[@]}" was expanded once at the start (lesson 100 showed the same behavior for indexed arrays):
declare -A g=([x]=1 [y]=2)
for k in "${!g[@]}"; do
g[$k$k]=9
echo "visit $k"
done
echo "count now ${#g[@]}"
visit y
visit x
count now 4
The loop ran twice, and the array grew to four keys (x, y, xx, yy).
Building Reports from Counts
Counting and then reporting is the most common use of iteration. This example counts color names, then prints the two most frequent:
words="red blue red green blue red yellow blue red"
declare -A f
for w in $words; do
f[$w]=$(( ${f[$w]:-0} + 1 ))
done
for w in "${!f[@]}"; do
echo "${f[$w]} $w"
done | sort -k1,1nr -k2 | head -n 2
4 red
3 blue
The first loop counts. ${f[$w]:-0} reads the current count or 0 for a new word, and the result is stored back; this form is safe under set -e, unlike (( f[$w]++ )) (lesson 102). The second loop prints count and word pairs, sort -k1,1nr orders them by count from high to low, -k2 breaks ties alphabetically by word, and head -n 2 keeps the top two.
Grouping Values Under a Key
An associative array value is a single string, but a string can hold a list. This example groups people by team, appending each name to its team's entry:
records=("ana:dev" "bo:ops" "cara:dev" "dan:ops" "eve:qa")
declare -A team
for r in "${records[@]}"; do
name=${r%%:*}
t=${r#*:}
team[$t]+="${team[$t]:+ }$name"
done
mapfile -t teams < <(printf '%s\n' "${!team[@]}" | sort)
for t in "${teams[@]}"; do
echo "$t: ${team[$t]}"
done
dev: ana cara
ops: bo dan
qa: eve
${r%%:*} keeps the part before the colon and ${r#*:} the part after it (lesson 54). In ${team[$t]:+ }, the :+ operator (lesson 45) produces a space only when the team already has a name, so the list never starts with a space. += then appends the space and the new name to the existing string.
Inverting a Table
Swapping keys and values builds a reverse lookup. Here a table of country codes becomes a table of names:
declare -A code=([IN]=India [JP]=Japan)
declare -A byname
for c in "${!code[@]}"; do
byname[${code[$c]}]=$c
done
echo "Japan -> ${byname[Japan]}"
Japan -> JP
This only works cleanly when every value is unique. If two keys share a value, the inverted table keeps whichever key the loop reached last, and because the loop order is the hash order, which one that is cannot be predicted.
Filling an Associative Array from a File
Configuration files of key = value lines map naturally onto an associative array. Given app.conf:
# comment
host = example.com
port = 8080
name = My App
this loop reads every setting, skipping blank lines and comments:
declare -A conf
while IFS='=' read -r key value; do
key=${key//[[:space:]]/}
[[ -z $key || $key == \#* ]] && continue
value=${value#"${value%%[![:space:]]*}"}
value=${value%"${value##*[![:space:]]}"}
conf[$key]=$value
done < app.conf
mapfile -t names < <(printf '%s\n' "${!conf[@]}" | sort)
for k in "${names[@]}"; do
echo "$k=[${conf[$k]}]"
done
host=[example.com]
name=[My App]
port=[8080]
What each part does:
IFS='=' read -r key valuesplits each line at the first=. Everything after it, including any further=signs, goes intovalue.${key//[[:space:]]/}removes all whitespace from the key.- The
continueline skips empty keys (blank lines) and keys starting with#(comments). The#is escaped so it is matched literally. - The two
value=lines trim leading and trailing whitespace from the value while keeping the space insideMy App. The inner expansion finds the run of whitespace at one end, and the outer expansion removes exactly that run. done < app.confredirects the file into the loop, so the loop runs in the current shell andconfkeeps its entries (lesson 80).
Reading the same data through a pipe would lose everything, because the loop at the end of a pipe runs in a subshell:
declare -A p=()
printf 'a=1\nb=2\n' | while IFS== read -r kk vv; do p[$kk]=$vv; done
echo "after pipe: ${#p[@]}"
while IFS== read -r kk vv; do p[$kk]=$vv; done < <(printf 'a=1\nb=2\n')
echo "after process substitution: ${#p[@]}"
after pipe: 0
after process substitution: 2
Use < file or < <(command) whenever a loop fills an array.
Joining Keys into One String
"${!arr[*]}" joins all keys into a single string, separated by the first character of IFS. Changing IFS inside a command substitution keeps the change local (lesson 98):
echo "keys joined: $(IFS=,; echo "${!o[*]}")"
keys joined: alpha,mid,beta,zeta
The order is again the hash order. For a stable result, join the sorted keys array instead.
Empty Associative Arrays
A loop over an empty associative array does not run, and its status is 0. In Bash 5.2 this also works in scripts with set -u:
declare -A none=()
for k in "${!none[@]}"; do echo never; done
echo "empty loop status $?"
set -u
for k in "${!none[@]}"; do :; done
echo "ok under set -u"
empty loop status 0
ok under set -u
The next lesson covers passing arrays, both indexed and associative, into functions, including the name references that let a function read and change the caller's array directly.