How to Use Associative Arrays in Bash: Syntax and Examples
In Bash, you create an associative array using
declare -A array_name. You can then assign values with keys like array_name[key]=value and access them using ${array_name[key]}.Syntax
To use an associative array in Bash, first declare it with declare -A. Then assign values using keys inside square brackets. Access values with ${array_name[key]}.
- declare -A array_name: Creates an associative array.
- array_name[key]=value: Assigns a value to a key.
- ${array_name[key]}: Retrieves the value for a key.
bash
declare -A my_array
my_array[key1]=value1
my_array[key2]=value2
# Access value
echo "${my_array[key1]}"Output
value1
Example
This example shows how to declare an associative array, add key-value pairs, and print all keys and values.
bash
declare -A colors colors[apple]=red colors[banana]=yellow colors[grape]=purple # Print a single value echo "Color of apple: ${colors[apple]}" # Loop through all keys and print key-value pairs for fruit in "${!colors[@]}"; do echo "$fruit is ${colors[$fruit]}" done
Output
Color of apple: red
apple is red
banana is yellow
grape is purple
Common Pitfalls
Common mistakes include forgetting to declare the array with declare -A, which makes Bash treat it as a normal indexed array. Also, keys must be quoted if they contain spaces or special characters.
Wrong: my_array[key with space]=value (no quotes)
Right: my_array["key with space"]=value
bash
declare -A my_array # Wrong: no quotes around key with space # my_array[key with space]=value # This causes an error # Right: quotes around key my_array["key with space"]=value echo "${my_array[\"key with space\"]}"
Output
value
Quick Reference
| Command | Description |
|---|---|
| declare -A array_name | Declare an associative array |
| array_name[key]=value | Assign value to a key |
| ${array_name[key]} | Access value by key |
| ${!array_name[@]} | Get all keys |
| ${array_name[@]} | Get all values |
Key Takeaways
Always declare associative arrays with declare -A before use.
Use quotes around keys if they contain spaces or special characters.
Access values with ${array_name[key]} and list keys with ${!array_name[@]}.
Associative arrays require Bash version 4.0 or higher.
Loop through keys to process all elements in the array.