0

I need to make one printable variable from echo output, I wrote this code, but seems that it not work:

myArray=('hello' 'hi')
arrayName="myArray"
arrayVar=1
echo $(echo -n '${' && echo -n "$arrayName" && echo -n '[' && echo -n "$arrayVar" && echo -n ']}')

Expected output:

hello

But it prints this:

${myArray[1]}

How can I fix it?

tdrkDev
  • 69
  • 4
  • The duplicate explains how to do indirection. It works equally well with arrays like in your case: `var="$arrayName[$arrayVar]"; echo "${!var}"`. Note that this results in `hi` rather than `hello` since bash arrays are 0-indexed. If you want `1` to refer to the first element in the array, you'll have to subtract one first. – that other guy Apr 13 '20 at 21:36
  • @thatotherguy this is small part of database on bash code (coronavirus isolation, week 4...), so first var of array is variable name, second var is variable data, third var is other variable name, and then like this... – tdrkDev Apr 13 '20 at 21:39

0 Answers0