2

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[*]}
triple fault
  • 13,410
  • 8
  • 32
  • 45

2 Answers2

4

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:

  • in the invoked function you have to reassemble the arguments back into an array yourself (though that's easy to do: reassembledArray=( "$@" )
  • if the input array was sparse, i.e, its indices aren't contiguous, this information is lost.

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
1

Call the function like this

 my_func "${arr[@]}"
quickshiftin
  • 66,362
  • 10
  • 68
  • 89