Bash Arrays Associative Arrays


Example

4.0

Declare an associative array

declare -A aa 

Declaring an associative array before initialization or use is mandatory.

Initialize elements

You can initialize elements one at a time as follows:

aa[hello]=world
aa[ab]=cd
aa["key with space"]="hello world"

You can also initialize an entire associative array in a single statement:

aa=([hello]=world [ab]=cd ["key with space"]="hello world")

Access an associative array element

echo ${aa[hello]}
# Out: world

Listing associative array keys

echo "${!aa[@]}"
#Out: hello ab key with space

Listing associative array values

echo "${aa[@]}"
#Out: world cd hello world

Iterate over associative array keys and values

for key in "${!aa[@]}"; do
    echo "Key:   ${key}"
    echo "Value: ${array[$key]}"
done

# Out:
# Key:   hello
# Value: world
# Key:   ab
# Value: cd
# Key:   key with space
# Value: hello world

Count associative array elements

echo "${#aa[@]}"
# Out: 3