Variable substitution in array printing

Hi folks,

A really dumb question as I've wasted far too long trying to get this to work.... (on RH bash)

I have an array:

m0[1]='<hello>'
m0[2]='<there>'
m0[3]='<fred>'

v0[1]='<goodbye>'
v0[2]='<again>'
v0[3]='<john>'

in my code I calculate the value of the variable to output and if I echo it, I get m0 or v0, but if I try and print the variable, I either get 3 as an output, or bad variable substitution, or no output.

 # $oc evaluates to m0 or v0

eval "printf '%s\n' \"\${#${oc}[@]}\""  (displays 3 as output)
#printf -- '%s\n' "${m0[@]}"  (displays correctly (when uncommented) but was just a test)
printf -- '%s\n' "${oc[@]}"  (no output)
printf -- '%s\n' "${$oc[@]}"  (bad variable substitution)

Thanks in advance - and apologies for the very basic question.

If you want to print it your will need to again use eval:

eval "printf '%s\n' \"\${${oc}[@]}\""
1 Like

Beware that, if your array contains an element like `rm -Rf ~/` eval will happily execute that code and delete your home directory. It evaluates all shell syntax, not just variables, but things in backticks and $( ) and > and any other possible syntax which might cause a malfunction, create unintended files, and/or blow up with syntax errors.