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 "The original array: ${my_arr[*]}" 
myfunc ${my_arr[*]} 

Because we used $1, it returns only the first array element.