Associative Arrays in Bash

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 102 of 205

An associative array stores values under string keys instead of numeric positions. Where an indexed array answers "what is the third item?", an associative array answers "what is the port for https?" or "how many times has the word error appeared?". Other languages call the same structure a dictionary, map or hash table. Bash has supported associative arrays since version 4.0.

Why Associative Arrays Exist

With only indexed arrays, related data has to be kept in parallel arrays (lesson 100): one array of names, another of values, joined by sharing the same index. Looking up a value then means searching the first array for the name and reading the second array at that position. An associative array does the lookup in one step, because the name itself is the index:

declare -A port=([http]=80 [https]=443 [ssh]=22)
echo "https -> ${port[https]}"
https -> 443

Internally Bash stores associative arrays as hash tables. A key is turned into a number (its hash) that points to a slot in a table, so finding a key does not require walking through every element. For scripts this means lookups stay fast even with thousands of keys.

Declaring an Associative Array

An associative array must be declared with declare -A before it is used. This is the one array type Bash cannot create automatically:

declare -A capital
capital[France]=Paris
capital[Japan]=Tokyo
capital["United Kingdom"]=London

echo "${capital[Japan]}"
echo "${capital[United Kingdom]}"
Tokyo
London

Each assignment has the form name[key]=value. A key that contains spaces is quoted in the assignment. When reading, the text between the brackets is taken as one key, so ${capital[United Kingdom]} works even without quotes, but keys are most often held in variables, and then the variable should be quoted like any other expansion:

key="United Kingdom"
echo "${capital[$key]}"
echo "count: ${#capital[@]}"
London
count: 3

${#arr[@]} counts the keys, exactly as it counts the elements of an indexed array (lesson 101).

Compound Assignment

All the pairs can be given at once inside parentheses, with each key in brackets:

declare -A port=([http]=80 [https]=443 [ssh]=22)
declare -p port
declare -A port=([ssh]="22" [https]="443" [http]="80" )

declare -p prints the type flag -A and every key with its value. Notice that the keys are not listed in the order they were written. Bash keeps them in hash-table order, not insertion order; lesson 103 shows how to process the keys in a predictable order.

Since Bash 5.1, the pairs can also be written as a flat list of key, value, key, value:

declare -A kv=(red 1 green 2)
declare -p kv
declare -A kv=([red]="1" [green]="2" )

The bracketed form works in every Bash version with associative arrays and is easier to read, so it is the one used in this tutorial.

What Happens Without declare -A

Forgetting the declaration does not cause an error. Bash creates an indexed array instead, and the keys are evaluated as arithmetic expressions. A word like apple is treated as the name of an unset variable, which counts as 0, so every key becomes index 0:

bad[apple]=1
bad[banana]=2
declare -p bad
echo "apple: ${bad[apple]}"
declare -a bad=([0]="2")
apple: 2

Both assignments wrote to index 0, the second overwrote the first, and asking for apple returned banana's value. Nothing in the output warns about this, which is why declare -A should always be the first line that mentions an associative array. declare -p is the quickest way to check: -a means indexed, -A means associative.

Once a variable is an indexed array, it cannot be converted:

late=(x y)
declare -A late
bash: declare: late: cannot convert indexed to associative array

unset late first, then declare it again.

Keys Are Strings

Every key in an associative array is a plain string, and nothing inside the brackets is evaluated as arithmetic. Keys that look like numbers are still compared as text:

declare -A num
num[1]=one
num[01]=zero-one
num[1+1]=expr
declare -p num
declare -A num=([01]="zero-one" [1]="one" [1+1]="expr" )

1, 01 and 1+1 are three different keys. Characters that are special elsewhere are also allowed when quoted:

declare -A k
k["a b"]=1
k['$HOME']=2
k[*]=3
declare -p k
declare -A k=(["*"]="3" ["\$HOME"]="2" ["a b"]="1" )

The single quotes around $HOME keep it as literal text rather than expanding it to a directory. The one string that cannot be a key is the empty string:

bash: ek[""]: bad array subscript

If a key comes from input that might be empty, check it with [[ -n $key ]] before using it.

Reading Missing Keys

Reading a key that was never assigned gives an empty string and no error:

echo "smtp: [${port[smtp]}]"
smtp: []

To tell a missing key from a key that holds an empty value, use the -v test with the element in quotes, or the ${arr[key]+word} expansion (both were introduced for indexed arrays in lesson 101 and behave the same way here):

if [[ -v 'port[ssh]' ]]; then echo "ssh is defined"; fi
if [[ ! -v 'port[smtp]' ]]; then echo "smtp is not defined"; fi

declare -A m=([empty]="")
[[ -v 'm[empty]' ]] && echo "empty key exists"
echo "plus: [${m[empty]+yes}] [${m[none]+yes}]"
ssh is defined
smtp is not defined
empty key exists
plus: [yes] []

When the key is in a variable, use double quotes so the variable expands but the whole element is still passed as one word: [[ -v "port[$name]" ]].

A missing key can also be given a fallback with the default-value operator from lesson 45:

echo "default: ${port[smtp]:-25}"
default: 25

This only supplies a value for that one expansion. The array itself is not changed.

Updating and Removing Keys

Assigning to an existing key replaces its value. unset with the element in quotes removes the key completely:

port[http]=8080
unset 'port[ssh]'
declare -p port
declare -A port=([https]="443" [http]="8080" )

The quotes around 'port[ssh]' matter for the same reason as with indexed arrays (lesson 99): unquoted, the brackets form a glob pattern that could match a file name in the current directory. To remove a key held in a variable, write unset 'port[$name]'; Bash expands $name itself when it looks up the element, so the single quotes are correct here.

To empty the array but keep it associative, assign an empty list:

port=()
declare -p port
declare -A port=()

Appending and Counting

+= on an element appends text to the value, because values are strings:

declare -A cnt=([x]=1)
cnt[x]+=5
echo "string append: ${cnt[x]}"
string append: 15

For numbers, use arithmetic. Inside (( )), an element of an associative array can be updated like a variable, and a missing key starts at 0:

declare -A ic
ic[x]=1
(( ic[x] += 5 ))
(( ic[new]++ ))
echo "arith: ${ic[x]}"
echo "new: ${ic[new]}"
arith: 6
new: 1

Alternatively, the -i attribute makes every value an integer, so += adds instead of appending:

declare -Ai score
score[ana]=5
score[ana]+=3
echo "ana: ${score[ana]}"
ana: 8

Counting Words

Counting is the classic use of an associative array. Each word becomes a key, and its value is the number of times it has been seen:

text="the cat and the dog and the bird"
declare -A freq
for w in $text; do
    (( freq[$w]++ ))
done
echo "the=${freq[the]} and=${freq[and]} cat=${freq[cat]}"
the=3 and=2 cat=1

$text is deliberately unquoted so that it splits into words (lesson 53). (( freq[$w]++ )) increases the count for the current word, creating the key with value 1 the first time.

One detail matters in scripts that use set -e (lesson 119): (( freq[$w]++ )) evaluates to the old value, which is 0 for a new key, and an arithmetic command whose result is 0 returns status 1. That status ends a set -e script on the first new word. Writing (( ++freq[$w] )) or freq[$w]=$(( ${freq[$w]:-0} + 1 )) avoids the problem, because both produce a non-zero value.

Associative Arrays in Functions

Inside a function, local -A creates an associative array that disappears when the function returns (lesson 92). This makes it a convenient scratch table, for example to detect duplicates:

find_duplicates() {
    local -A seen=()
    local x
    for x in "$@"; do
        if [[ -v "seen[$x]" ]]; then
            echo "duplicate: $x"
        fi
        seen[$x]=1
    done
    echo "unique: ${#seen[@]}"
}

find_duplicates a b a c b
duplicate: a
duplicate: b
unique: 3

Only the presence of a key matters here, so the value 1 is a placeholder. Using an associative array as a set in this way is common: checking membership is one -v test instead of a loop over a list. After the function returns, seen no longer exists.

Copying an Associative Array

Writing copy=("${original[@]}") copies only the values and loses the keys. To copy keys and values, declare the target and copy each pair:

declare -A src=([a]=1 [b]=2)
declare -A dst
for k in "${!src[@]}"; do
    dst[$k]=${src[$k]}
done
echo "dst a=${dst[a]} b=${dst[b]}"
dst a=1 b=2

"${!src[@]}" expands to the list of keys. Lesson 103 covers this loop and its variations in detail.

Limits to Keep in Mind

Values are single strings. A value cannot itself be an array. Lists are kept as strings with a separator (lesson 100 showed read -a splitting such a string), or in a second array.

Associative arrays cannot be exported. As with indexed arrays (lesson 97), a child process does not receive them, even with declare -Ax:

declare -Ax ex=([a]=1)
bash -c 'echo "[${ex[a]}]"'
[]

They need Bash 4.0 or later. The Bash 3.2 shipped as /bin/bash on macOS does not have them (lesson 8 explains how to install a newer Bash there). Other shells such as Dash, used as sh on Debian and Ubuntu, do not have declare at all. A three-line script assoc.sh containing declare -A m, m[a]=1 and echo ok, run with sh assoc.sh, prints:

assoc.sh: 1: declare: not found
assoc.sh: 2: m[a]=1: not found
ok

Dash reports each line as an unknown command and carries on, so the script keeps running with no array at all.

Scripts that use associative arrays should start with a Bash shebang (lesson 26) and be run with bash, not sh.

A Practical Lookup Table

Associative arrays turn chains of if or case branches into data. This script maps file extensions to a description and falls back to a default for anything unknown:

#!/usr/bin/env bash
declare -A kind=(
    [sh]="shell script"
    [py]="Python source"
    [md]="Markdown document"
    [jpg]="JPEG image"
)

for f in deploy.sh notes.md photo.jpg data.bin; do
    ext=${f##*.}
    echo "$f: ${kind[$ext]:-unknown type}"
done
deploy.sh: shell script
notes.md: Markdown document
photo.jpg: JPEG image
data.bin: unknown type

${f##*.} removes everything up to the last dot (lesson 54), leaving the extension, which is then used as the key. Adding a new file type is one more line in the table, with no change to the loop. The compound assignment may span several lines, and each [key]=value pair can sit on its own line for readability.

The next lesson looks at walking through all the keys and values of an associative array, sorting them, and building reports from them.

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 Associative Arrays in Bash and get answers drawn from it.

Signed-in readers only.