help-bash
[Top][All Lists]
Advanced

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

Re: Functions takes arrays and outputting another array


From: Greg Wooledge
Subject: Re: Functions takes arrays and outputting another array
Date: Fri, 31 Mar 2023 13:29:43 -0400

On Fri, Mar 31, 2023 at 04:58:35PM +0000, uzibalqa wrote:
> I want to make a bash function that takes two arrays and outputs another 
> array.

Bash has no "pass by reference" capability.  The closest it has is
the "name reference" variable type (declare -n), which is a hack that
requires careful working-around within the function that uses it.

Bash "functions" also cannot return values to their callers.  So, even
returning a simple string is already a challenge.  Trying to return an
array, even more so.

See <https://mywiki.wooledge.org/BashProgramming/#Functions> for some
more discussion and some tricks.

With the proper safeguarding in place, you can use name references to
pass the names of two arrays as parameters to the function.

foo() {
    declare -n _foo_a1="$1"
    declare -n _foo_a2="$2"
    local _foo_i _foo_j

    for _foo_i in "${_foo_a1[@]}"; do
        for _foo_j in "${_foo_a2[@]}"; do
            ...
        done
    done
}

How you want to handle *returning* an array is a separate matter.  The
most obvious way would be to pass the output array name as a third
parameter, and use a third name reference inside the function.

Of course, other ways are possible.

>     printf '%s\0" "${_out[@]}"

This produces an output stream which can be read into an array by the
caller.  Presumably you were planning to run something like

    mapfile -d '' myarray < <(myfunc array1 array2)

which means your function runs in a forked background subshell.  This
is certainly a viable choice, and if your function is only called once,
the single fork() isn't too terrible of a performance hit (in a language
that's already slow).

There is no single right answer here.



reply via email to

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