help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Passing multiple arrays to a function


From: Greg Wooledge
Subject: Re: [Help-bash] Passing multiple arrays to a function
Date: Tue, 11 Dec 2018 09:15:39 -0500
User-agent: NeoMutt/20170113 (1.7.2)

On Tue, Dec 11, 2018 at 09:00:24AM -0500, Jerry wrote:
> I am trying to pass arrays to a function. I can get it to work if I only pass
> one function; however, I cannot figure out how to pass two or more arrays
> simultaneously.
[...]
> ## Call the function
> 
> standing "address@hidden" "address@hidden"

How does your function know where the first list ends, and the second
list begins?

If you want to pass two lists to a function on the argument vector,
you need to pass a special sentinel value as a separator.  This sentinel
will have to be something that cannot occur in the first list.  Then,
you'll need to iterate over the argument vector, assigning elements to
a local array until the special sentinel is found.

Other approaches may also be considered.  For instance, you can simply
hard-code the names of the arrays inside the function, and not pass
them at all.  Or, you could dump the lists into files, and pass the
names of the files to the function, which can then read the lists from
the files.  Or, you could pass one list on the argument vector, and
the other list as a stream on standard input, and have the function
read the stream into an array.

Or, if you are especially brave (or foolish), you could attempt to use
bash 4.3's name reference feature, and pass the names of the arrays
on the argument vector, and then have the function attempt to use
namerefs to point to the arrays in the caller's scope.  Be warned that
doing this will NEVER be 100% safe, because there is no way to prevent
the caller from passing an array whose name matches one of your
function's local variables.  And if that happens, shit blows up.

The best you can do with namerefs is obfuscate the name of every single
local variable inside the function using some scheme that the caller
is unlikely to use.  If the caller is malicious, you're just screwed,
but you can try to minimize the odds of an accident.



reply via email to

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