help-bash
[Top][All Lists]
Advanced

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

Re: Locas arrays to functions


From: Greg Wooledge
Subject: Re: Locas arrays to functions
Date: Mon, 1 May 2023 18:03:47 -0400

On Mon, May 01, 2023 at 09:41:00PM +0000, uzibalqa wrote:
> I was under the impression that arrays are always global when passed to a 
> function 
> as a positional argument.  Should they be passed as reference?
> 
> local -n _array="$2"

Passing the NAME of an array as an argument to a function, and then using
a nameref (local -n) inside the function, is one possible way to get
things done.

This approach has all the same limitations as passing a string variable
"by reference".  The nameref's value is resolved as a variable name,
with bash's dynamic scoping rules, meaning it first searches for a
matching variable in the function's scope, then in the calling function's
scope, then in the caller's caller's scope, and so on.

Every piece of advice that I've given REPEATEDLY concerning string
variable namerefs applies to this case as well.

If you've forgotten my advice, see
<https://mywiki.wooledge.org/BashProgramming/#Functions>.

> Would I need the quotes as in "$2" ?

Using them will never hurt.  Realistically, either you control the caller,
or you do not.  If you control the caller, then you know that you're
passing only safe, sensible variable names.  If you do not, then the
"variable name" that you receive in the called function needs to be
sanity-checked, or else there is a risk of code injection.  Double quoting
won't be enough to save you in that case.



reply via email to

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