As ugly as it is, here is a workaround that works as long as you aren't passing an array explicitly, but a variable corresponding to an array:
function passarray()
{
eval array_internally=("$(echo '${'$1'[@]}')")
# access array now via array_internally
echo "${array_internally[@]}"
#...
}
array=(0 1 2 3 4 5)
passarray array # echo's (0 1 2 3 4 5) as expected
I'm sure someone can come up with a clearnercleaner implementation of the idea, but I've found this to be a better solution than passing an array as "{array[@]"}
and then accessing it internally using array_inside=("$@")
. This becomes complicated when there are other positional/getopts
parameters. In these cases, I've had to first determine and then remove the parameters not associated with the array using some combination of shift
and array element removal.
A purist perspective likely views this approach as a violation of the language, but pragmatically speaking, this approach has saved me a whole lot of grief. On a related topic, I also use eval
to assign an internally constructed array to a variable named according to a parameter target_varname
I pass to the function:
eval $target_varname=$"(${array_inside[@]})"
Hope this helps someone.
eval $target_varname=$"(${array_inside[@]})"