bash how to pass array to function

Answer

To pass all array items as arguments to the function use 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 example of function "array_echo" which writes all items of 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 echo command does't output the trailing newline.

Actually, it is not passing array as variable, but as a list of its elements. In our example you can not change values of array items from function array_echo().

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.