如何将数组传递给 bash 函数

发布于 2024-12-14 22:05:57 字数 268 浏览 0 评论 0原文

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

$ 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉鱼一梦 2024-12-21 22:05:57
#!/bin/bash
ar=( a b c )
test() {
    local ref=$1[@]
    echo ${!ref}
}

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

test ar
嗼ふ静 2024-12-21 22:05:57

我意识到这个问题已经有近两年的历史了,但它帮助我找到了原始问题的实际答案,而上述答案实际上都没有做到这一点(@ata 和 @l0b0 的答案)。问题是“如何将数组传递给 bash 函数?”,虽然 @ata 接近正确,但他的方法最终并没有得到在函数本身中使用的实际数组。需要补充一点。

因此,假设我们在调用函数 do_something_with_array() 之前在某处有 anArray=(abcd),这就是我们定义该函数的方式:

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

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

现在

do_something_with_array anArray

将正确输出:

4
d

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

local tmp=$1[@]
prevIFS=$IFS
IFS=,
local arrArg=(${!tmp})
IFS=$prevIFS

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
江南烟雨〆相思醉 2024-12-21 22:05:57

ar 不是要测试的第一个参数 - 它是所有 参数。您必须在函数中echo“$@”

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文