Bash: Use Associative Array

From WikiMLT

Sim­ple ex­am­ple

cat bash-associative-array-simple.sh
#!/bin/bash

declare -A content_cats
content_cats=(
    ["WordPress"]="This category contains..."
    ["MediaWiki"]="This category contains..."
    ["HTML and CSS"]="This category contains..."
    ["Linux Desktop"]="This category contains..."
    ["Linux Server"]="This category contains..."
)

for key in "${!content_cats[@]}"; do
  echo -e "$key \t => ${content_cats[$key]}"
done
./bash-associative-array-simple.sh
MediaWiki        => This category contains...
Linux Desktop    => This category contains...
HTML and CSS     => This category contains...
Linux Server     => This category contains...
WordPress        => This category contains...

Ex­tend­ed ex­am­ple

As you can see in the above ex­am­ple the ar­ray con­tent is print­ed in wrong or­der. We can solve this is­sue by the fol­low­ing ap­proach, pro­vid­ed by Jonathan Lef­fler at Stack Over­flow, where is used one ad­di­tion­al ar­ray that holds the prop­er or­der.

cat bash-associative-array-extended.sh
#!/bin/bash

declare -A content_cats
content_cats=(
    ["WordPress"]="This category contains..."
    ["MediaWiki"]="This category contains..."
    ["HTML and CSS"]="This category contains..."
    ["Linux Desktop"]="This category contains..."
    ["Linux Server"]="This category contains..."
)

declare -a content_cats_order
content_cats_order=(
    "WordPress"
    "MediaWiki"
    "HTML and CSS"
    "Linux Desktop"
    "Linux Server"
)

for key in "${content_cats_order[@]}"
do
    echo -e "$key \t => ${content_cats[$key]}"
done
./bash-associative-array-extended.sh
WordPress        => This category contains...
MediaWiki        => This category contains...
HTML and CSS     => This category contains...
Linux Desktop    => This category contains...
Linux Server     => This category contains...

Ref­er­ence man­u­al

Ref­er­ences