Iterating Over Associative Arrays

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 103 of 205

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:

ExpansionIndexed arrayAssociative array
"${arr[@]}"all valuesall values
"${!arr[@]}"all indexes (numbers)all keys (strings)
${#arr[@]}number of elementsnumber 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:

  1. printf '%s\n' "${!stock[@]}" repeats its format for every key, producing one key per line.
  2. sort orders the lines. sort -r would reverse them, and sort -f would ignore case.
  3. < <( ... ) feeds the sorted lines to mapfile in the current shell, so the keys array still exists after the line runs. Piping into mapfile instead would run it in a subshell and lose the result (lesson 98).
  4. mapfile -t strips the newline from each line, so every element of keys is exactly one key, spaces included.
  5. The loop then walks keys in order and looks up each value. %-14s left-aligns the key in 14 columns and %5d right-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,1 sorts on the first field only.
  • n compares the field as a number, so 150 comes after 12 rather than before it.
  • r reverses 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 value splits each line at the first =. Everything after it, including any further = signs, goes into value.
  • ${key//[[:space:]]/} removes all whitespace from the key.
  • The continue line 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 inside My App. The inner expansion finds the run of whitespace at one end, and the outer expansion removes exactly that run.
  • done < app.conf redirects the file into the loop, so the loop runs in the current shell and conf keeps 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Iterating Over Associative Arrays and get answers drawn from it.

Signed-in readers only.