如何将数组传递给 bash 函数
如何将数组传递给函数,为什么这不起作用? 其他问题的解决方案对我不起作用。 根据记录,我不需要复制数组,所以我不介意传递引用。我想做的就是循环它。
$ 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我意识到这个问题已经有近两年的历史了,但它帮助我找到了原始问题的实际答案,而上述答案实际上都没有做到这一点(@ata 和 @l0b0 的答案)。问题是“如何将数组传递给 bash 函数?”,虽然 @ata 接近正确,但他的方法最终并没有得到在函数本身中使用的实际数组。需要补充一点。
因此,假设我们在调用函数
do_something_with_array()
之前在某处有anArray=(abcd)
,这就是我们定义该函数的方式:现在
将正确输出:
如果有数组中的某些元素可能包含空格,您应该将
IFS
设置为 SPACE 以外的值,然后在将函数的数组 arg(s) 复制到本地数组后返回。例如,使用上面的: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 functiondo_something_with_array()
, this is how we would define the function:Now
Would correctly output:
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:ar
不是要测试的第一个参数 - 它是所有 参数。您必须在函数中echo“$@”
。ar
is not the first parameter to test - It is all the parameters. You'll have toecho "$@"
in your function.