如何将数组传递给 bash 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8082947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an array to a bash function
提问by johndir
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
采纳答案by ata
#!/bin/bash
ar=( a b c )
test() {
local ref=[@]
echo ${!ref}
}
test ar
回答by Gus Shortz
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.
我意识到这个问题已经有将近两年的历史了,但它帮助我找出了原始问题的实际答案,而上述答案实际上都没有(@ata 和 @l0b0 的答案)。问题是“我如何将数组传递给 bash 函数?”,虽然@ata 接近正确,但他的方法最终并没有在函数本身中使用实际数组。需要少量添加。
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:
所以,假设我们anArray=(a b c d)在调用 function 之前有某个地方do_something_with_array(),这就是我们定义函数的方式:
function do_something_with_array {
local tmp=[@]
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 IFSto 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:
如果数组的某些元素可能包含空格,则应设置IFS为 SPACE 以外的值,然后在将函数的数组 arg(s) 复制到本地数组后返回。例如,使用上面的:
local tmp=[@]
prevIFS=$IFS
IFS=,
local arrArg=(${!tmp})
IFS=$prevIFS
回答by l0b0
aris not the first parameter to test - It is allthe parameters. You'll have to echo "$@"in your function.
ar不是要测试的第一个参数 - 它是所有参数。你必须echo "$@"在你的函数中。

