Here's a concise guide to Bash associative arrays:
-
Declare: declare -A myarray
-
Add elements: myarray[key1]=value1 myarray[key2]=value2
-
Access element: ${myarray[key1]}
-
List all keys: ${!myarray[@]}
-
List all values: ${myarray[@]}
-
Number of elements: ${#myarray[@]}
-
Remove element: unset myarray[key1]
-
Check if key exists: [[ -v myarray[key1] ]]
-
Iterate: for key in "${!myarray[@]}"; do echo "$key: ${myarray[$key]}" done
-
Clear array: unset myarray
Note: Requires Bash 4.0+