Bash How to Pass Array to Function
To pass all array items as arguments to the function using the following syntax:
my_function "${array[@]}"
To get values from the array in function use:
array_in_function=("$@")
If you would use “$1” instead of (“$@”) you get the first item from the array, “$2”-second item and etc.
Here is an example of the function “array_echo” which writes all items of the array.
function array_echo() { arr=("$@") for i in "${arr[@]}"; do echo -n "$i " done } array=(1 2 3 4 5 ) array_echo "${array[@]}"
Note: The “n” option in the echo command doesn’t output the trailing newline.
Actually, it is not passing an array as a variable, but as a list of its elements. In our example, you can not change values of array items from function array_echo().