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 (???).

2
  • 1
    You want "$@" if this is bash. See this question. Commented Aug 1, 2013 at 18:59
  • @Troy My argument is an array(single argument). Looks like it's different from combination of several arguments Commented Aug 1, 2013 at 19:06

1 Answer 1

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*
Sign up to request clarification or add additional context in comments.

3 Comments

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:>
That seems an arbitrary requirement. Why restrict yourself that way when it just makes your life harder?
Yes.You are right. Anyway thanks a lot for your reply.Looks very good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.