In another question to stackoverflow, I asked how to pass array to a function. An answer recommended me a previous answers. One answer suggests that declare with -n option, referencing, is useful to pass array to an function, like following,
declare -a array=( 1 2 )
function array_pass_by_reference_func() {
local -n aug=${1:-dummy}
echo "pass by reference : array[0] = ${aug[0]}"
echo "pass by reference : array[1] = ${aug[1]}"
echo "pass by reference : array = ${aug[@]}"
}
# execute an example function above
array_pass_by_reference_func "array"
# output
pass by reference : array[0] = 1
pass by reference : array[1] = 2
pass by reference : array = 1 2
It looks working well. My question here is about an instruction of declare -n in bash manual,
The -n attribute cannot be applied to array variables.
I would like to confirm that can I pass array to a function with declare -n option? My original question is marked as duplicated and the previous question is too old to ask this question. So please let me ask it here. Thank you very much.
Further down on the man
page, under the PARAMETERS
heading, it also says:
However, nameref variables can reference array variables and subscripted array variables.
In other words:
declare -a -n foo=...
will result in a syntax error).Therefore, your approach should be safe.
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