Passing arrays

Not all your passed values will be single values; you may need to pass an array to the function. Let's see how to pass an array as a parameter:

#!/bin/bash 
myfunc() { 
   arr=$@ 
   echo "The array from inside the function: ${arr[*]}" 
} 
 
test_arr=(1 2 3) 
echo "The original array is: ${test_arr[*]}" 
myfunc ${test_arr[*]} 

From the result, you can see that the used array is returned the way it is from the function.

Note that we used $@ to get the array inside the function. If you use $1, it will return the first array element only:

#!/bin/bash myfunc() { arr=$1 echo "The array from inside the function: ${arr[*]}" } my_arr=(5 10 15) echo ...

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.