[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Incorrect / Inconsistent behavior with nameref assignments in functi

From: Greg Wooledge
Subject: Re: Incorrect / Inconsistent behavior with nameref assignments in functions
Date: Fri, 28 Aug 2020 13:17:26 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Fri, Aug 28, 2020 at 06:20:04PM +0200, Binarus wrote:
> However, the main question is why leaving away the -a and -i in the
> second script makes things work as expected.

I'll leave aside my usual rant about -i for now.  Here's your original


function Dummy() {

  local -n namerefArray="$1"
  local -a -i myArray=("${namerefArray[@]}")

  local -p

declare -a -i myArray=('1' '2' '3')

Dummy 'myArray'

Here's a variant of it, to try to figure out what's going on.

unicorn:~$ cat f1

f() {
  local -n ref="$1"
  local -a -i myArray=("${ref[@]}" 420 69)
  local -p

declare -a -i myArray=('1' '2' '3')
f 'myArray'
declare -p myArray
unicorn:~$ ./f1
myArray=([0]="420" [1]="69")
declare -ai myArray=([0]="1" [1]="2" [2]="3")

Here we can see that a local array variable is created, and populated with
our two static elements.  After returning from the function, the caller's
array is still untouched, so we did not trample the global variable.
It was definitely local.

So the "error" here appears to be that the expansion of "${ref[@]}"
results in zero words.

If we take out the -i then we get the same result.

If we put the -i back in and take out the -a, we also get the same result.

If we take out BOTH the -a and the -i, then we get:

unicorn:~$ ./f1
myArray=([0]="1" [1]="2" [2]="3" [3]="420" [4]="69")
declare -ai myArray=([0]="1" [1]="2" [2]="3")

Your guess is as good as mine what's happening here.  I'll just continue
to stick with my defensive programming.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]