How can I make this code work?
#!/bin/bash
ARRAYNAME='FRUITS'
FRUITS=( APPLE BANANA ORANGE )
for FRUIT in ${!ARRAYNAME[@]}
do
echo ${FRUIT}
done
This code:
echo ${!ARRAYNAME[0]}
Prints APPLE. I’m tryng to do something similar but with “[@]” to iterate over the array.
Thanks in advance,
${!ARRAYNAME[@]}means “the indices ofARRAYNAME“. As stated in the bash man page sinceARRAYNAMEis set, but as a string, not an array, it returns0.Here’s a solution using
eval.What you were originally trying to do was create an Indirect Reference. These were introduced in bash version 2 and were meant to largely replace the need for
evalwhen trying to achieve reflection-like behavior in the shell.What you have to do when using indirect references with arrays is include the
[@]in your guess at the variable name:All that said, it’s one thing to use Indirect References in this trivial example, but, as indicated in the link provided by Dennis Williamson, you should be hesitant to use them in real-world scripts. They are all but guaranteed to make your code more confusing than necessary. Usually you can get the functionality you need with an Associative Array.