Just as in other programming languages, associative arrays in Bash are useful for search, set management, and keying into a list of values. The label may be different, but whether called “map”, “dictionary”, or “associative array”, the same concepts apply.
In its simplest form, here is an initialization and then loop through the key/value pairs.
declare -A pets pets=( ["dog"]="fido" ["cat"]="mr kitty" ["bird"]="whistler" ) # iterate over keys for petkey in "${!pets[@]}"; do echo "I have a $petkey named ${pets[$petkey]}" done
Which outputs:
I have a cat named mr kitty I have a dog named fido I have a bird named whistler
Iterating over just the values (not keys):
# iterate over values for petval in "${pets[@]}"; do echo "I have a pet named $petval" done
outputs:
I have a pet named mr kitty I have a pet named fido I have a pet named whistler
Another example
A more complex example where Java spring profiles are selected depending on which environment is being deployed could look like this:
# multi-dimensional arrays not supported so using spaces to fake array declare -A endpoints springprofiles=( ["test"]="test docker mysql" ["prod"]="prod kubernetes postgresql" ) # select target environment SELECTED_PROFILE="prod" envprofiles=${springprofiles[$SELECTED_PROFILE]} # loop through each word in list for profile in $envprofiles; do echo "$SELECTED_PROFILE needs profile $profile" done
And would produce this when ‘prod’ is the target environment:
prod needs profile prod prod needs profile kubernetes prod needs profile postgresql
REFERENCES
linuxhint, associative arrays in Bash