0

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. Then in the function, I want to iterate through the array like:

(in my_function)

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

What should be the correct syntax for (???).

4

1 に答える 1

1

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
}

2 番目の場合は、単純に"$@"orを使用します。

my_function() {
    local -a ary=("$@")
    # 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*
于 2013-08-01T19:25:39.170 に答える