我给阵列作为参数传递给这样的功能:壳牌脚本数组语法
declare -a my_array=(1 2 3 4)
my_function (????my_array)
我想要的阵列被传递给函数,正如一个阵列,而不是作为4个独立的参数。然后在功能,我想通过像数组遍历:
(以创建my_function)
for item in (???)
do
....
done
什么应该是正确的语法(???)。
我给阵列作为参数传递给这样的功能:壳牌脚本数组语法
declare -a my_array=(1 2 3 4)
my_function (????my_array)
我想要的阵列被传递给函数,正如一个阵列,而不是作为4个独立的参数。然后在功能,我想通过像数组遍历:
(以创建my_function)
for item in (???)
do
....
done
什么应该是正确的语法(???)。
bash没有数组文字的语法。您显示的内容(my_function (1 2 3 4)
)是语法错误。您必须使用
my_function "(1 2 3 4)"
my_function 1 2 3 4
一个第一:
my_function() {
local -a ary=$1
# do something with the array
for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}
对于第二,只需使用"[email protected]"
或:
my_function() {
local -a ary=("[email protected]")
# do something with the array
for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}
一个不情愿的编辑...
my_function() {
local -a ary=($1) # $1 must not be quoted
# ...
}
declare -a my_array=(1 2 3 4)
my_function "${my_array[#]}" # this *must* be quoted
这依赖于你的数据不包含空格。例如,这将不起作用
my_array=("first arg" "second arg")
你想通过2个元素,但是你会收到4强制转换数组转换成字符串,然后再扩展它是充满了危险。
你可以用间接变量做到这一点,但他们是丑陋与阵列
my_function() {
local tmp="${1}[@]" # just a string here
local -a ary=("${!tmp}") # indirectly expanded into a variable
# ...
}
my_function my_array # pass the array *name*
嗨,感谢您的回复。它工作得很好。但是,我遇到了另一个问题。我已经更新了我原来的帖子。你可以看看:> Bash对我来说很新,有时候我只是陷入了一些简单的问题:> –
这似乎是一个任意的要求。为什么用这种方式来限制自己,当它让你的生活变得更难? –
是的。你说得对。无论如何非常感谢您的答复。看起来非常好。 –
你想要的“$ @”如果这是bash的。看[这个问题](http://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-bash-script)。 – Troy
@Troy我的参数是一个数组(单个参数)。看起来它不同于几个参数的组合 –