1

I am trying to get the size of an array, but I don't know the array name until runtime (it's built dynamically based on a list from a file), so I am trying to use bash indirection with ${!var}.

This answer comes very close (How to iterate over an array using indirect reference?), but falls short of making the array size ${#var[@]} work

Note: I am trying to avoid eval, and I have Bash >=4.0 but <4.3 (so I cannot use declare -n). And I'd rather not iterate over the whole array to calculate size, as it can get very large.

What I have working:

# Declare dynamic arrays
for env in INT PROD; do
    declare -A "values$env"
done
# Creates 'valuesINT[]' and valuesPROD[]' arrays

while IFS=$'\n'=, read -r key env val; do
    # Assigns val to index key in dynamic array name values$env
    declare "values$env[$key]=$val"
done <my_file

# Output arrays
for env in INT PROD; do
    valuesArrName="values${env}[@]"
    echo ${!valuesArrName} # this works to output all values
done

So I can use indirection with ${!valuesArrName} to output values

But I cannot use indirection to get array size:

valuesArrName="values${env}[@]"
echo ${#!valuesArrName} 
# OUTPUT: ${#!valuesArrName}: bad substitution

valuesArrName="#values${env}[@]"
echo ${!valuesArrName}
# OUTPUT: #valuesINT[@]: bad substitution

valuesArrName="#values${env}"
echo ${!valuesArrName[@]}
# OUTPUT: no error, but always 0
Slav
  • 27,057
  • 11
  • 80
  • 104

0 Answers0