[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Passing multiple arrays to a function
From: |
Dmitry Alexandrov |
Subject: |
Re: [Help-bash] Passing multiple arrays to a function |
Date: |
Wed, 13 Feb 2019 19:01:10 +0300 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux) |
Greg Wooledge <address@hidden> wrote:
> 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"
>
> 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.
>
> <...>
>
> 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.
Hmm. I was under impression that Bash execute statements strictly
sequentially, so all you need in order to avoid such a collision is to simply
put an assignment of positional arguments to something meaningful _before_
declarations of any other local variables (which I would do nevertheless, just
because it’s easier to grasp); i. e.:
#!/bin/bash
array_1=("PASS")
array_2=("1 foo" "2 foo")
unsafe-fn ()
{
local array_1=('FAIL')
local a=("${!1}") b=("${!2}")
printf '%s;' "address@hidden" "address@hidden"
printf '\n'
}
safe-fn ()
{
local a=("${!1}") b=("${!2}")
local array_1=('FAIL')
printf '%s;' "address@hidden" "address@hidden"
printf '\n'
}
unsafe-fn 'address@hidden' 'address@hidden'
safe-fn 'address@hidden' 'address@hidden'
FAIL;1 foo;2 foo;
PASS;1 foo;2 foo;
Do I miss anything? It is still faulty in some other way?
signature.asc
Description: PGP signature
- Re: [Help-bash] Passing multiple arrays to a function,
Dmitry Alexandrov <=