[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: |
Fri, 15 Feb 2019 06:44:13 +0300 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux) |
Greg Wooledge <address@hidden> wrote:
> On Wed, Feb 13, 2019 at 07:01:10PM +0300, Dmitry Alexandrov wrote:
>> safe-fn ()
>> {
>> local a=("${!1}") b=("${!2}")
>> local array_1=('FAIL')
>> printf '%s;' "address@hidden" "address@hidden"
>> printf '\n'
>> }
>>
>> safe-fn 'address@hidden' 'address@hidden'
>
> Oh my gods, it's *THAT* hack again.
You mean indirectly addressing elements of array by its read representation
(ref='arr[i]'; echo "${!ref}"), don’t you?
> I don't know where it came from (other than "try a bunch of shit and
> see if it works"), or how it got such a foothold in people's minds.
Alas, I cannot recall when and where exactly I personally learned this, but for
past several years most people, I believe, get to known about it from your
incredible collection of Bash hacks and tricks [1].
[1] https://mywiki.wooledge.org/BashFAQ/006?action=diff&rev1=24&rev2=23
> I have nothing good to say about that hack. At some point a couple
> years ago, we asked Chet whether it was actually a supported thing,
> or whether a future bug-fix of the parser might make it stop behaving
> this way, and the answer was inconclusive.
>
> In any case, you are not using namerefs here, so my warnings about
> nameref collisions simply do not apply.
This is perfectly possible with namerefs as well:
#!/bin/bash
array_1=("PASS")
array_2=("1 foo" "2 foo")
nameref-safe-fn ()
{
local -n a_ref=$1 b_ref=$2
local a=("address@hidden") b=("address@hidden")
local array_1=('FAIL')
printf '%s;' "address@hidden" "address@hidden"
printf '\n'
}
nameref-safe-fn array_1 array_2
PASS;1 foo;2 foo;
signature.asc
Description: PGP signature