如何将数组传递给bash函数

joh*_*dir 12 arrays bash shell

如何将数组传递给函数,为什么这不起作用?其他问题的解决方案对我不起作用.为了记录,我不需要复制数组,所以我不介意传递引用.我想做的就是循环它.

$ 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
Run Code Online (Sandbox Code Playgroud)

ata*_*ata 11

#!/bin/bash
ar=( a b c )
test() {
    local ref=$1[@]
    echo ${!ref}
}

test ar
Run Code Online (Sandbox Code Playgroud)

  • 在"$ {!ref}"中使用`for pkg',否则循环对于数组元素中的空格将是脆弱的(例如`ar =(a"b c"d)`). (2认同)

Gus*_*rtz 5

我意识到这个问题已经差不多两年了,但它帮助我找出了原始问题的实际答案,上面的答案实际上都没有(@ata和@ l0b0的答案).问题是"如何将数组传递给bash函数?",而@ata接近正确,他的方法最终没有在函数本身内使用的实际数组.需要一个小的补充.

所以,假设我们anArray=(a b c d)在调用函数之前有某个地方do_something_with_array(),这就是我们定义函数的方式:

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

    echo ${#arrArg[*]}
    echo ${arrArg[3]}
}
Run Code Online (Sandbox Code Playgroud)

现在

do_something_with_array anArray
Run Code Online (Sandbox Code Playgroud)

会正确输出:

4
d
Run Code Online (Sandbox Code Playgroud)

如果您的数组中的某些元素可能包含空格,则应将其设置IFS为SPACE以外的值,然后在将函数的数组arg(s)复制到本地数组后返回.例如,使用以上内容:

local tmp=$1[@]
prevIFS=$IFS
IFS=,
local arrArg=(${!tmp})
IFS=$prevIFS
Run Code Online (Sandbox Code Playgroud)