简体   繁体   English

Shell脚本数组语法

[英]Shell script array syntax

I give an array as a parameter to a function like this: 我将数组作为参数传递给这样的函数:

 declare -a my_array=(1 2 3 4)  
 my_function  (????my_array)

I want the array to be passed to the function just as one array, not as 4 separate argument. 我希望将数组作为一个数组而不是作为4个单独的参数传递给函数。 Then in the function, I want to iterate through the array like: 然后在函数中,我想像这样遍历数组:

(in my_function) (在my_function中)

for item in (???) 
do 
.... 
done

What should be the correct syntax for (???). (???)的正确语法应该是什么。

bash does not have a syntax for array literals. bash没有数组文字的语法。 What you show ( my_function (1 2 3 4) ) is a syntax error. 您显示的内容( my_function (1 2 3 4) )是语法错误。 You must use one of 您必须使用以下之一

  • my_function "(1 2 3 4)"
  • my_function 1 2 3 4

For the first: 为了第一:

my_function() {
    local -a ary=$1
    # do something with the array
    for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}

For the second, simply use "$@" or: 对于第二个,只需使用"$@"或:

my_function() {
    local -a ary=("$@")
    # do something with the array
    for idx in "${!ary[@]}"; do echo "ary[$idx]=${ary[$idx]}"; done
}

A reluctant edit... 一个勉强的编辑...

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

This relies on your data NOT containing whitespace. 这取决于您的数据不包含空格。 For example this won't work 例如,这行不通

my_array=("first arg" "second arg")

You want to pass 2 elements but you will receive 4. Coercing an array into a string and then re-expanding it is fraught with peril. 您希望传递2个元素,但您将收到4个元素。将数组强制转换为字符串,然后重新扩展该数组将充满风险。

You can do this with indirect variables, but they are ugly with arrays 您可以使用间接变量来执行此操作,但使用数组很难做到这一点

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*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM