Haiyuan Zhang
Haiyuan Zhang

Reputation: 42792

how to use array as function variable in bash

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:

Upvotes: 1

Views: 256

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125798

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[@]}"

Upvotes: 2

user unknown
user unknown

Reputation: 36229

#!/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.

Upvotes: 2

sirgeorge
sirgeorge

Reputation: 6531

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
}

Upvotes: 1

Related Questions