Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirect parameter expansion of an array argument in Bash

Tags:

bash

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?

like image 804
Calaf Avatar asked Feb 14 '23 08:02

Calaf


1 Answers

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"
like image 133
glenn jackman Avatar answered Mar 08 '23 17:03

glenn jackman