Using a name reference in a recent (>=4.3) version of bash
:
foo () {
local param1=$1
local -n arr=$2
printf 'array: %s\n' "${arr[@]}"
}
myarray=( some items go here )
foo something myarray
The name of the array variable is passed as the second parameter to the function. The function declares a name reference variable that receives this name. Any access to that name reference variable will access the variable whose name was passed to the function.
This obviously works with more than one array.
Note that in the example above, you can not pass a variable named arr
to the function, so some care has to be taken to avoid name clashes (ksh93
, which also supports name references, don't have this issue due to different scoping).
Note that this approach does not work when calling another shell script. When calling another shell script, the array has to be passed on the command line of that other script, which means it has to be passed as a set of strings. To pass a single array this way is relatively easy, and Hauke Laging shows the basics of how to do this in his answer.
If you have full control over the contents of the arrays, you may be able to encode their data as single strings, possibly by delimiting their elements using some delimiter and then parsing these strings in the target script to re-form the arrays. Another possibility would be to adopt a JSON "interface" between your scripts, meaning you would encode the data as JSON, pass it on the scripts standard input (or similar), and decode the document using jq
. This does feel rather cumbersome though, and it would add a massive overhead.
my_func
has an array. Is my edit correct? – Tim Jun 05 '18 at 17:33