1

I want to pass an array parameter to a function in bash, and writing some testing code as:

 #!/bin/sh

    function foo {
       a=$1;
       for i in ${a[@]} ; do
          echo $i
       done
    }
    names=(jim jerry jeff)
    foo ${names[@]}

the above code just show jim, rather than the three j*. so my question is:

  • why my code doesn't work
  • what's the right way to do it

3 Answers 3

2
#!/bin/bash
function foo {
a=($*)
for i in ${a[@]}
do
    echo $i
done
}

names=(jim jerry jeff)
foo ${names[@]}

Your code did not show jim to me, but "names", literally. You have to pass the whole array. And you have to recapture it with a=$($).

The manpage part in bash about Arrays is rather long. I only cite one sentence:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.

Sign up to request clarification or add additional context in comments.

1 Comment

@HaiyuanZhang: Btw.: When using the bash, use the Bash-Shebang.
2

You're fairly close; the biggest problem was the command a=$1, which assigns only the first parameter ($1) to a, while you want to assign the entire list of parameters ($@), and assign it as an array rather than as a string. Other things I corrected: you should use double-quotes around variables whenever you use them to avoid confusion with special characters (e.g. spaces); and start the script with #!/bin/bash, since arrays are a bash extension, not always available in a brand-X shell.

#!/bin/bash

function foo {
    a=("$@")
    for i in "${a[@]}" ; do
        echo "$i"
    done
}

names=(jim jerry jeff "jim bob")
foo "${names[@]}"

Comments

1

For example like this:

my_array[0]="jim"
my_array[1]="jerry"

function foo
{
    #get the size of the array
    n=${#my_array[*]}
    for (( Idx = 0; Idx < $n; ++Idx  )); do
            echo "${my_array[$Idx]}"
    done
}

3 Comments

thanks but I want to get a local copy of the array to prevent the original one being changed
Did you try to pass it to the function with the '$' like : foo ${names} ?
Sorry about that but in the above example you do not do that correctly :)

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.