0
0
Bash Scriptingscripting~5 mins

Associative arrays (declare -A) in Bash Scripting

Choose your learning style9 modes available
Introduction
Associative arrays let you store data with named keys instead of numbers. This helps you organize information like a mini-dictionary.
When you want to store user info like name and age together.
When you need to map file names to their sizes.
When you want to count how many times each word appears in a text.
When you want to store configuration settings with names and values.
When you want to quickly look up data by a meaningful label.
Syntax
Bash Scripting
declare -A array_name
array_name[key]=value
value=${array_name[key]}
Use declare -A to create an associative array in bash.
Keys and values are strings, and keys can be any text.
Examples
Create an associative array user with keys name and age. Then print the values.
Bash Scripting
declare -A user
user[name]="Alice"
user[age]=30

# Access
echo "Name: ${user[name]}"
echo "Age: ${user[age]}"
Shows how to declare an empty associative array and check if it has no elements.
Bash Scripting
declare -A empty_array

# Check if empty
if [ ${#empty_array[@]} -eq 0 ]; then
  echo "Array is empty"
fi
Store color names and their hex codes, then loop over keys to print all pairs.
Bash Scripting
declare -A colors
colors[red]="#FF0000"
colors[green]="#00FF00"
colors[blue]="#0000FF"

# Print all keys
for key in "${!colors[@]}"; do
  echo "$key -> ${colors[$key]}"
done
Sample Program
This script creates an associative array called capitals. It stores countries as keys and their capitals as values. It prints all pairs, then prints the capital of Japan.
Bash Scripting
#!/bin/bash

# Declare associative array
declare -A capitals

# Add some countries and their capitals
capitals[France]="Paris"
capitals[Japan]="Tokyo"
capitals[Kenya]="Nairobi"

# Print all countries and capitals
for country in "${!capitals[@]}"; do
  echo "$country: ${capitals[$country]}"
done

# Access a single capital
echo "Capital of Japan is ${capitals[Japan]}"
OutputSuccess
Important Notes
Accessing keys uses ${!array[@]} to get all keys.
Time complexity for lookup is very fast, like a dictionary.
Common mistake: forgetting to declare with -A causes errors or numeric indexing.
Use associative arrays when you want named keys instead of just numbers.
Summary
Associative arrays store data with named keys for easy lookup.
Declare with declare -A before using keys and values.
Use loops with ${!array[@]} to access all keys.