bash does not have a syntax for array literals. What you show (my_function (1 2 3 4)
) is a syntax error. You must use one of
my_function "(1 2 3 4)"
my_function 1 2 3 4
For the first:
my_function() {
local -a ary=$1
# do something with the array
for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}
For the second, simply use "$@"
or:
my_function() {
local -a ary=("$@")
# do something with the array
for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}
A reluctant edit...
my_function() {
local -a ary=($1) # $1 must not be quoted
# ...
}
declare -a my_array=(1 2 3 4)
my_function "${my_array[#]}" # this *must* be quoted
This relies on your data NOT containing whitespace. For example this won't work
my_array=("first arg" "second arg")
You want to pass 2 elements but you will receive 4. Coercing an array into a string and then re-expanding it is fraught with peril.
You can do this with indirect variables, but they are ugly with arrays
my_function() {
local tmp="${1}[@]" # just a string here
local -a ary=("${!tmp}") # indirectly expanded into a variable
# ...
}
my_function my_array # pass the array *name*