Is there a way to pass an array into function as a single argument?
I tried the following which didn't work:
arr=(a b c)
my_func $arr
and also
arr(a b c)
my_func ${arr[*]}
Is there a way to pass an array into function as a single argument?
I tried the following which didn't work:
arr=(a b c)
my_func $arr
and also
arr(a b c)
my_func ${arr[*]}
Passing "${arr[@]}"
(@quickshiftin's answer) kind of works, but it's important to note that it doesn't pass an array, but the array's elements as individual arguments, accessible to the invoked functions as $1
, $2
, ...
This has the following implications:
reassembledArray=( "$@" )
The short of it: there's no way to pass arrays as such.
That said, if you're invoking a function rather than a script, your function will have access to all variables in the current shell, so you could simply directly access an array variable defined in the same shell before the function call.
Example:
my_func() {
echo "Elements of arr:"
for el in "${arr[@]}"; do echo "[$el]"; done
}
arr=(a b c)
my_func