You can, sort of. Bash and ksh93 have name references, which are somewhat like pointers and allow you to pass the array name to the function, and use it from there, say:
#!/bin/bash
function byname {
typeset -n _p=$1
echo "second item of '$1' is ${_p[1]}"
echo "second arg to this function is \"$2\""
}
blah=(a b c)
byname blah "other arg"
Though in Bash, the name of the nameref (_p
here) must be different from the name of the variable it points to, so it's not very usable with recursive functions. In ksh it works with the same name only in ksh style functions (function foo
instead of foo()
).
As the label says, that's a reference, not a copy, so if you modify the array in the function, the changes show in the main program.
The other, worse, alternative is to concatenate the array to a string, and pass it as a variable:
function concated {
echo "the whole array is \"$1\""
}
concated "${blah[*]}"
But that pretty much defeats the point of using an array in the first place, unless you come up with some elaborate system for array to string packing.
The above calls of course print:
second item of 'blah' is b
second arg to this function is "other arg"
the whole array is "a b c"
inside
func()`. – cas Jan 22 '18 at 09:44