Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can namerefs (declare -n) be used with arrays in bash? What does the documentation mean when it says declare -n cannot be applied to arrays?

Tags:

bash

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.

like image 243
mora Avatar asked Mar 11 '23 16:03

mora


1 Answers

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:

  • You can't declare a nameref variable itself as an array (declare -a -n foo=... will result in a syntax error).
  • But a nameref variable can reference an array.

Therefore, your approach should be safe.

like image 87
mklement0 Avatar answered Apr 28 '23 01:04

mklement0