How to pass an array to a bash function

2020-05-26 12:08发布

How do I pass an array to a function, and why wouldn't this work? The solutions in other questions didn't work for me. For the record, I don't need to copy the array so I don't mind passing a reference. All I want to do is loop over it.

$ ar=(a b c)
$ function test() { echo ${1[@]}; }
$ echo ${ar[@]}
a b c
$ test $ar
bash: ${1[@]}: bad substitution
$ test ${ar[@]}
bash: ${1[@]}: bad substitution

3条回答
▲ chillily
2楼-- · 2020-05-26 12:25
#!/bin/bash
ar=( a b c )
test() {
    local ref=$1[@]
    echo ${!ref}
}

test ar
查看更多
劳资没心,怎么记你
3楼-- · 2020-05-26 12:34

I realize this question is almost two years old, but it helped me towards figuring out the actual answer to the original question, which none of the above answers actually do (@ata and @l0b0's answers). The question was "How do I pass an array to a bash function?", while @ata was close to getting it right, his method does not end up with an actual array to use within the function itself. One minor addition is needed.

So, assuming we had anArray=(a b c d) somewhere before calling function do_something_with_array(), this is how we would define the function:

function do_something_with_array {
    local tmp=$1[@]
    local arrArg=(${!tmp})

    echo ${#arrArg[*]}
    echo ${arrArg[3]}
}

Now

do_something_with_array anArray

Would correctly output:

4
d

If there is a possibility some element(s) of your array may contain spaces, you should set IFS to a value other than SPACE, then back after you've copied the function's array arg(s) into local arrays. For example, using the above:

local tmp=$1[@]
prevIFS=$IFS
IFS=,
local arrArg=(${!tmp})
IFS=$prevIFS
查看更多
姐就是有狂的资本
4楼-- · 2020-05-26 12:35

ar is not the first parameter to test - It is all the parameters. You'll have to echo "$@" in your function.

查看更多
登录 后发表回答