Skip to content

Instantly share code, notes, and snippets.

@dinhoabreu
Created September 24, 2021 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinhoabreu/2e852f508f92f1122672dcdeef0bda86 to your computer and use it in GitHub Desktop.
Save dinhoabreu/2e852f508f92f1122672dcdeef0bda86 to your computer and use it in GitHub Desktop.
Bash - Associative Array
#!/usr/bin/env bash
a2l() {
jq '.[] | (.name, .value)' <<-EOF
[
{ "name": "x", "value": "v1 vv1" },
{ "name": "y", "value": "v2 vv2" },
{ "name": "z", "value": "v3 vv3" }
]
EOF
}
declare -A dict=()
while read -r key; do
read -r value
dict["${key:1:-1}"]="${value:1:-1}"
done < <(a2l)
# list keys
echo keys: "${!dict[@]}"
# list values
echo values: "${dict[@]}"
# get value by key
echo get: "x=${dict[x]} y=${dict[y]} z=${dict[z]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment