📝 Edit page
➕ Add page
Associative arrays
Syntax
Create
declare -A MY_ARRAY
Update
MY_ARRAY[abc]=def
You can have spaces in a key.
MY_ARRAY[abc xyz]=def
Retrieve
echo MY_ARRAY[abc]
# def
Get keys
Show all keys.
$ declare -A MYMAP=( [foo]=bar [fizz buzz]=123 )
$ echo "${!MYMAP[@]}"
foo fizz buzz
Loop through all keys.
$ for K in "${!MYMAP[@]}"; do echo $K; done
foo
fizz buzz
Values
Loop through all values.
$ for V in "${MYMAP[@]}"; do echo $V; done
bar
123
Deleting values
See Bash associative array examples.
Examples
Define and then set values:
declare -A MY_ENVS
MY_ENVS[d]=develop
MY_ENVS[s]=stage
MY_ENVS[p]=production
Define and then set values in one line:
declare -A MY_ENVS=([d]=develop [s]=stage [p]=production)
Sample usage to lookup:
echo ${MY_ENVS[d]}
# develop
ENV='d'
TARGET_ENV=${MY_ENVS[$ENV]}
echo $TARGET_ENV
# develop