How can one expand a parameter when the parameter is an array?
If the parameter is a simple variable, we can do an indirection using an exclamation point.
single_fruit()
{
if [ "$#" != 1 ]; then exit 1; fi
echo ${!1}
}
MYVAR=Persimmon
single_fruit MYVAR
I'd like to do the same on an array parameter. Rather than iterate over the elements of an array directly:
FRUIT=(Papaya Pineapple)
for f in ${FRUIT[@]}
do
echo ${f}
done
I'd like to iterate within a function:
multi_fruit()
{
if [ "$#" != 1 ]; then exit 1; fi
PARAMETER=${1}
for i in ${!PARAMETER[@]}
do
echo ${i}
done
}
MOREFRUITS=(Mango Melon)
multi_fruit MOREFRUITS
Can you make this last function iterate over the array elements?
You can do it, but in an unexpected way: the placeholder var needs to include the array index:
multi_fruit() {
(( $# != 1 )) && return 1
tmp="${1}[@]"
for i in "${!tmp}"; do
echo "$i"
done
}
Also, it's a bad idea to use only uppercase variable names. One day you'll accidentally overwrite PATH and wonder why your script is broken. Leave uppercase vars to the system.
Also note that putting braces around the variable is not the same as double quotes. For example, consider:
var="one two three"
printf "%s\n" ${var}
printf "%s\n" "$var"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With