In the code snippet below, I found that, when trying to pass multiple arrays to a function in Bash, I am able to do so using the syntax in my first example, but only if:
- The array variable names are prefixed with an underscore (_)
- The array variable names are otherwise identically named in the receiving function as the calling function
function list_arrays {
local _array_one=$1
local _array_two=$2
for ip in "${array_one[@]}"; do
echo "$ip"
done
for node in "${array_two[@]}"; do
echo "$node"
done
}
function main {
local array_one=( 1 2 3 4 5 )
local array_two=( one two three four five )
list_arrays "${array_one[@]}" "${array_two[@]}"
}
main
Output:
1
2
3
4
5
one
two
three
four
five
Changing the example slightly to remove the underscores...
#!/bin/bash
function list_arrays {
local array_one=$1
local array_two=$2
for ip in "${array_one[@]}"; do
echo "$ip"
done
for node in "${array_two[@]}"; do
echo "$node"
done
}
function main {
local array_one=( 1 2 3 4 5 )
local array_two=( one two three four five )
list_arrays "${array_one[@]}" "${array_two[@]}"
}
main
Output:
1
2
One last iteration to change the name of the array variables in the list_arrays function
#!/bin/bash
function list_arrays {
local _array_first=$1
local _array_second=$2
for ip in "${_array_first[@]}"; do
echo "$ip"
done
for node in "${_array_second[@]}"; do
echo "$node"
done
}
function main {
local array_one=( 1 2 3 4 5 )
local array_two=( one two three four five )
list_arrays "${array_one[@]}" "${array_two[@]}"
}
main
Output:
(no output)
The behavior is extremely convenient but I want to understand what I'm doing before I use this in production scripts. At first I thought this might be related to pass-by-reference. However, this syntax works in Bash 4.1 which seems to be before pass-by-reference was added.
list_arraysthat are distinct from those inmain.