Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #16829

Re: Incorrect / Inconsistent behavior with nameref assignments in functions

From Greg Wooledge <wooledg@eeg.ccf.org>
Newsgroups gnu.bash.bug
Subject Re: Incorrect / Inconsistent behavior with nameref assignments in functions
Date 2020-08-28 11:28 -0400
Message-ID <mailman.1615.1598628531.2469.bug-bash@gnu.org> (permalink)
References <a20e4692-69b3-9836-4861-3e822e407ef7@binarus.de> <20200828152846.GI931@eeg.ccf.org>

Show all headers | View raw


On Fri, Aug 28, 2020 at 10:56:34AM +0200, Binarus wrote:
> #!/bin/bash
> 
> function Dummy() {
> 
>   local -n namerefArray="$1"
>   local -a -i myArray=("${namerefArray[@]}")
> 
>   local -p
> }
> 
> declare -a -i myArray=('1' '2' '3')

You've got a local variable with the same name as the global variable
that you're attempting to pass by reference.  This will not work.

Namerefs (declare -n) in bash are *not* like uplevel commands in Tcl.
They cause the referenced variable name to be evaluated just like any
other variable would be, starting at the current function scope, then
going up to the caller, and so on.

If you want to use namerefs in a function in bash, you MUST go out of
your way to minimize the chances of a collision between the caller's
variable refererance and ANY local variable of the function.  Not just
the nameref itself, but any other incidental variables used in the
function.  (As you aptly demonstrated here.)

So, you can't write functions like this:

func1() {
  declare -n ref="$1"
  local i
  ...
}

Instead, you need crazy things like this:

func1() {
  declare -n _func1_ref="$1"
  local _func1_i
  ...
}

And then you just have to pray that the caller respects you enough not
to use variables named with _func1_ prefixes.

There is no 100% bulletproof solution to this issue.

See also <https://mywiki.wooledge.org/BashProgramming#Functions>.

Back to gnu.bash.bug | Previous | Next | Find similar


Thread

Re: Incorrect / Inconsistent behavior with nameref assignments in functions Greg Wooledge <wooledg@eeg.ccf.org> - 2020-08-28 11:28 -0400

csiph-web