0

I give an array as a parameter to a function like this:

 declare -a my_array=(1 2 3 4)  
 my_function  (????my_array)

I want the array to be passed to the function just as one array, not as 4 separate argument. Then in the function, I want to iterate through the array like:

(in my_function)

for item in (???) 
do 
.... 
done

What should be the correct syntax for (???).

Hao Shen
  • 2,605
  • 3
  • 37
  • 68
  • 1
    You want "$@" if this is bash. See [this question](http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script). – Troy Aug 01 '13 at 18:59
  • @Troy My argument is an array(single argument). Looks like it's different from combination of several arguments – Hao Shen Aug 01 '13 at 19:06

1 Answers1

1

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*
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Hi,thanks for your reply. It's working very well. However, I met another problem. I have updated my original post.Could you take a look:> Bash is very new to me and sometimes I just got stuck on some simple problem:> – Hao Shen Aug 01 '13 at 20:37
  • That seems an arbitrary requirement. Why restrict yourself that way when it just makes your life harder? – glenn jackman Aug 02 '13 at 02:51
  • Yes.You are right. Anyway thanks a lot for your reply.Looks very good. – Hao Shen Aug 02 '13 at 13:07