I have put much time in trying to understand the behavior described below, but without success. Please consider the following code:
#!/bin/bash
function Dummy() {
local -n namerefArray="$1"
local -a -i myArray=("${namerefArray[@]}")
local -p
}
declare -a -i myArray=('1' '2' '3')
Dummy 'myArray'
The output is:
root@cerberus:~/scripts# ./test6
myArray=()
namerefArray=myArray
That is, the assignment in the second line in the function body destroys the content of the variable which is referenced by the nameref.
Originally, this made me scratch my head until I understood that this line actually expands to
local -a -i myArray=("${myArray[@]}")
if $1 is myArray as in the example. So I am assigning a (yet undefined) array variable (to be precise, its expansion) to itself.
Obviously, in a function, bash can't distinguish between a local variable and a nameref variable if the referenced variable has the same name as the local one. So far, so good (rather, so far, so bad, because this actually makes namerefs worthless, but this is another story and not subject of the question).
Then I tried the following code:
#!/bin/bash
function Dummy() {
local -n namerefArray="$1"
local myArray=("${namerefArray[@]}")
local -p
}
declare -a -i myArray=('1' '2' '3')
Dummy 'myArray'
Please note that it is literally the same as the first example, except that -a -i is missing in the second line of the function body.
But now the output is:
root@cerberus:~/scripts# ./test6
myArray=([0]="1" [1]="2" [2]="3")
namerefArray=myArray
That is, this time the array has been copied as expected, and the variable referenced by the nameref has not been emptied.
Could somebody please explain why -a -i in the second line of the function body makes such an important difference? I'd really like to understand it.
UPDATE
This originally happened with bash 4.2.12 in an up-to-date vanilla debian stretch installation. In the meantime, I have tried it with bash 5.0.3 in an up-to-date debian buster installation, with exactly the same result.
I can hardly imagine that such a bug could go unresolved for at least 3 years, so it perhaps is intended behavior?
UPDATE 2
In the meantime, I even tried with bash 5.0.11, with the same result.