I'm trying to iterate over the last several entries of an associative array in a bash script - in this case to sum up their value. I've tried the following:
SUM="0"
for last_element in $(printf "%s\n" "${!ELEMENTS[@]}" | tail -100); do
ELEMENT_SUM="$(echo "scale=5; $SUM + ${ELEMENTS[$last_elements]}" | bc)"
done
What happens in practice is the the $last_element prints out the entire list (of 100 elements in this case), instead of iterating over each - and thus the ${ELEMENTS[$last_elements]} fails.
I've tried multiple approaches (including negative indexing - ${ELEMENTS[-100]} for example) with no luck. I'm not sure what it is I'm doing wrong...
Any pointers and ideas would be greatly appreciated.
Thanks!