'How to get a last key of an associative array (dictionary)
How I can have an access to the last key of the associative array in bash? In this example I need to have "lot" in the $last variable. I found a way described here: How to get the keys and values of an associative array indirectly in Bash?. But it doesn't work as expected in the example below and return this error:
./test.sh: line 9: keys2: ${!$addict[@]}: must use subscript when assigning associative array
Here are the contents of this test.sh:
declare -A addict=(
["foo"]="bar"
["few"]="baz"
["lot"]="pot"
)
index_last=$(( ${#addict[@]} - 1 ))
eval 'declare -A keys2=(${!$addict[@]})'
last="${keys2[$index_last]}"
echo "$keys2"
echo "$index_last"
echo "$last"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
