[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Functions takes arrays and outputting another array
From: |
Jesse Hathaway |
Subject: |
Re: Functions takes arrays and outputting another array |
Date: |
Tue, 4 Apr 2023 11:32:26 -0500 |
On Fri, Mar 31, 2023 at 11:59 AM uzibalqa <uzibalqa@proton.me> wrote:
>
> I want to make a bash function that takes two arrays and outputs another
> array.
>
> Here I use "typeset". Should I use "declare" instead as in (declare -n
> _array1="$1" _array2="$2") ?
>
> For the output, I have thought about introducing a null. Is this the correct
> way to output arrays
> from a function?
Another fun way to pass arrays by value, though not particularly
performant, is to use stdin and stdout to pass their values. As an example
here I pass an array to a function via stdin and then pass the
result via stdout.
#!/bin/bash
function type_value {
IFS='=' read -r _ var
printf '%s\n' "$var"
}
function reverse_array {
read -r val
eval 'a='"$val"
declare -a rev_a
# shellcheck disable=SC2154
len=${#a[@]}
for ((i = (len - 1); i >= 0; i--)); do
rev_a+=("${a[i]}")
done
declare -p rev_a | type_value
}
# shellcheck disable=SC2034
butter=(a b c d e f g)
eval 'bubbles='"$(declare -p "butter" | type_value | reverse_array)"
# shellcheck disable=SC2154
declare -p bubbles
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Re: Functions takes arrays and outputting another array,
Jesse Hathaway <=