The question is perfectly valid and don't think its a duplicate of Passing arrays as parameters in bash.
The problem with passing the array as argument to the function as "${nodes[@]}"
or ${nodes[@]}
in this case would be at the receiving side, the array contents are not kept intact, because the contents of the array is expanded before the function is called. So when the arguments are unpacked at the receiver, they are split at $1
, $2
till the size of the array. You could see it from this simple example,
set -x
newf() { echo "$1"; echo "$2"; echo "$3"; }
arr=(1 2 3)
newf "${arr[@]}"
+ newf 1 2 3
+ echo 1
1
+ echo 2
2
+ echo 3
3
as you can see the array arr
is expanded to the list of positional arguments while the intention was to use an array.
So given this problem and with your claim that you have additional argument flags after the array, you need to identify in the receiver side, how to start processing arguments after the array. The best way would be to pass the array expansion using *
, so that the elements quoted as a whole.
So assuming your function expects 3 arguments to it, you can define it as below. The read
command on the receiver will split the whole string of array content to individual elements and store it in the array arrayArgs
and you can parse it as you wish.
is_node(){
(( $# < 3 )) && { printf 'insufficient args provided' >&2; return 1; }
read -ra arrayArgs <<<"$1"
printf 'Printing the array content \n'
for element in "${arrayArgs[@]}"; do
printf '%s\n' "$element"
done
printf '2nd arg=%s 3rd arg=%s\n' "$2" "$3"
}
and pass the array as
list=(1 2 3)
is_node "${list[*]}" 4 5