如何将数组作为参数传递给bash函数?
注意:在Stack Overflow上找不到答案后,我自己发布了一个有点粗糙的解决方案。它只允许传递一个数组,并且它是参数列表的最后一个元素。实际上,它根本没有传递数组,而是传递数组元素的列表,这些元素被called_function()重新组装成一个数组,但它对我来说是有效的。如果有人知道更好的方法,请在这里添加。
如何将数组作为参数传递给bash函数?
注意:在Stack Overflow上找不到答案后,我自己发布了一个有点粗糙的解决方案。它只允许传递一个数组,并且它是参数列表的最后一个元素。实际上,它根本没有传递数组,而是传递数组元素的列表,这些元素被called_function()重新组装成一个数组,但它对我来说是有效的。如果有人知道更好的方法,请在这里添加。
当前回答
这里的基本问题是,设计/实现数组的bash开发人员真的把事情搞砸了。他们认为${array}只是${array[0]}的简称,这是一个严重的错误。特别是当您认为${array[0]}没有意义并且如果数组类型是关联的,则计算结果为空字符串时。
Assigning an array takes the form array=(value1 ... valueN) where value has the syntax [subscript]=string, thereby assigning a value directly to a particular index in the array. This makes it so there can be two types of arrays, numerically indexed and hash indexed (called associative arrays in bash parlance). It also makes it so that you can create sparse numerically indexed arrays. Leaving off the [subscript]= part is short hand for a numerically indexed array, starting with the ordinal index of 0 and incrementing with each new value in the assignment statement.
因此,${array}应该计算为整个数组,索引和所有。它的求值应该是赋值语句的倒数。任何计算机科学专业的三年级学生都应该知道这一点。在这种情况下,这段代码将完全按照你所期望的那样工作:
declare -A foo bar
foo=${bar}
然后,按值将数组传递给函数并将一个数组分配给另一个数组将按照shell语法的其余部分执行。但是因为他们做得不对,赋值操作符=对数组不起作用,并且数组不能通过值传递给函数或子shell或一般的输出(echo ${array}),而没有代码来仔细检查它。
因此,如果做得正确,那么下面的例子将显示数组在bash中的用处可以大大提高:
simple=(first=one second=2 third=3)
echo ${simple}
结果输出应该是:
(first=one second=2 third=3)
然后,数组可以使用赋值操作符,并按值传递给函数甚至其他shell脚本。通过输出到文件很容易存储,也很容易从文件加载到脚本中。
declare -A foo
read foo <file
可惜的是,一个顶级的bash开发团队让我们失望了。
因此,要将数组传递给函数,实际上只有一个选项,那就是使用nameref特性:
function funky() {
local -n ARR
ARR=$1
echo "indexes: ${!ARR[@]}"
echo "values: ${ARR[@]}"
}
declare -A HASH
HASH=([foo]=bar [zoom]=fast)
funky HASH # notice that I'm just passing the word 'HASH' to the function
将导致以下输出:
indexes: foo zoom
values: bar fast
由于这是通过引用传递的,所以也可以在函数中为数组赋值。是的,被引用的数组必须具有全局作用域,但考虑到这是shell脚本,这应该不是太大的问题。要将一个关联或稀疏索引数组按值传递给一个函数,需要将所有索引和值作为单个字符串扔到参数列表中(如果是一个大数组,则不太有用),如下所示:
funky "${!array[*]}" "${array[*]}"
然后在函数内部写一堆代码来重新组装数组。
其他回答
下面的答案向您展示了如何通过序列化和反序列化将bash常规“索引”数组作为参数传递给函数。
To see this manual serializing/deserializing for bash associative arrays (hash tables) instead of for regular indexed arrays, see my answer here. For a better way (which requires bash version 4.3 or later, I think), which passes the arrays by reference, see the link just above and my other answer here. Passing arrays by reference is much easier and more-concise, so that's what I now recommend. That being said, the manual serializing/deserializing techniques I show below are also extremely informative and useful.
快速总结:
请参阅下面的3个单独的函数定义。我复习了一下如何通过:
一个bash数组对应一个函数 两个或多个bash数组到一个函数,和 一个函数的两个或多个bash数组加上额外的参数(在数组之前或之后)。
12年过去了,我仍然没有看到任何我真正喜欢的答案,我认为这些答案足够彻底,足够简单,足够“规范”,足以让我使用——这些答案我可以一次又一次地回来,在需要时复制、粘贴和扩展。所以,这是我的答案,我认为是所有这些事情。
如何将bash数组作为参数传递给bash函数
您也可以将其称为“bash函数或脚本中的可变参数解析”,特别是因为传递给下面示例的每个数组中的元素数量可以动态变化,并且在bash中,数组的元素本质上是作为单独的输入参数传递给函数,即使是通过“${array1[@]}”这样的单个数组展开参数传入数组。
对于下面的所有示例代码,假设你有这两个bash数组用于测试:
array1=()
array1+=("one")
array1+=("two")
array1+=("three")
array2=("four" "five" "six" "seven" "eight")
上面和下面的代码可以在我的bash/array_pass_as_bash_parameter.sh文件在我的eRCaGuy_hello_world repo上GitHub。
例1:如何将一个bash数组传递给函数
要将数组传递给bash函数,必须分别传递数组的所有元素。给定bash数组array1,获取该数组所有元素的语法是"${array1[@]}"。由于bash函数或可执行文件的所有传入参数都包装在名为@的神奇bash输入参数数组中,因此可以使用“$@”语法读取输入数组的所有成员,如下所示。
函数定义:
# Print all elements of a bash array.
# General form:
# print_one_array array1
# Example usage:
# print_one_array "${array1[@]}"
print_one_array() {
for element in "$@"; do
printf " %s\n" "$element"
done
}
使用示例:
echo "Printing array1"
# This syntax passes all members of array1 as separate input arguments to
# the function
print_one_array "${array1[@]}"
示例输出:
Printing array1
one
two
three
例2:如何将两个或多个bash数组传递给一个函数…
(以及如何再次将输入数组重新捕获为单独的bash数组)
Here, we need to differentiate which incoming parameters belong to which array. To do this, we need to know the size of each array, meaning the number of elements in each array. This is very similar to passing arrays in C, where we also generally must know the array length passed to any C function. Given bash array array1, the number of elements in it can be obtained with "${#array1[@]}" (notice the usage of the # symbol). In order to know where in the input arguments the array_len length parameter is, we must always pass the array length parameter for each array before passing the individual array elements, as shown below.
为了解析数组,我对输入参数数组@使用数组切片。
这里有一个关于bash数组切片语法如何工作的提示(来自我的回答)。在切片语法:start:length中,第一个数字是开始切片的从零开始的索引,第二个数字是要抓取的元素的数量:
# array slicing basic format 1: grab a certain length starting at a certain
# index
echo "${@:2:5}"
# │ │
# │ └────> slice length
# └──────> slice starting index (zero-based)
# array slicing basic format 2: grab all remaining array elements starting at a
# certain index through to the end
echo "${@:2}"
# │
# │
# └──────> slice starting index (zero-based)
此外,为了迫使输入数组中的切片参数变成一个新数组,我用圆括号()将它们括起来,例如("${@:$ I:$array1_len}")。外面的括号很重要,因为这是我们在bash中创建数组的方式。
下面的示例只接受两个bash数组,但是按照给定的模式,它可以很容易地接受任意数量的bash数组作为参数。
函数定义:
# Print all elements of two bash arrays.
# General form (notice length MUST come before the array in order
# to be able to parse the args!):
# print_two_arrays array1_len array1 array2_len array2
# Example usage:
# print_two_arrays "${#array1[@]}" "${array1[@]}" \
# "${#array2[@]}" "${array2[@]}"
print_two_arrays() {
# For debugging: print all input args
echo "All args to 'print_two_arrays':"
print_one_array "$@"
i=1
# Read array1_len into a variable
array1_len="${@:$i:1}"
((i++))
# Read array1 into a new array
array1=("${@:$i:$array1_len}")
((i += $array1_len))
# Read array2_len into a variable
array2_len="${@:$i:1}"
((i++))
# Read array2 into a new array
array2=("${@:$i:$array2_len}")
((i += $array2_len))
# Print the two arrays
echo "array1:"
print_one_array "${array1[@]}"
echo "array2:"
print_one_array "${array2[@]}"
}
使用示例:
echo "Printing array1 and array2"
print_two_arrays "${#array1[@]}" "${array1[@]}" "${#array2[@]}" "${array2[@]}"
示例输出:
Printing array1 and array2
All args to 'print_two_arrays':
3
one
two
three
5
four
five
six
seven
eight
array1:
one
two
three
array2:
four
five
six
seven
eight
例3:向一个函数传递两个bash数组和一些额外的参数
这是上面例子的一个小扩展。它还使用bash数组切片,就像上面的示例一样。但是,我们不是在解析两个完整的输入数组后停止,而是在最后继续解析更多的参数。这种模式可以无限地延续到任意数量的bash数组和任意数量的附加参数,以适应任何输入参数的顺序,只要每个bash数组的长度恰好在该数组的元素之前。
函数定义:
# Print all elements of two bash arrays, plus two extra args at the end.
# General form (notice length MUST come before the array in order
# to be able to parse the args!):
# print_two_arrays_plus_extra_args array1_len array1 array2_len array2 \
# extra_arg1 extra_arg2
# Example usage:
# print_two_arrays_plus_extra_args "${#array1[@]}" "${array1[@]}" \
# "${#array2[@]}" "${array2[@]}" "hello" "world"
print_two_arrays_plus_extra_args() {
i=1
# Read array1_len into a variable
array1_len="${@:$i:1}"
((i++))
# Read array1 into a new array
array1=("${@:$i:$array1_len}")
((i += $array1_len))
# Read array2_len into a variable
array2_len="${@:$i:1}"
((i++))
# Read array2 into a new array
array2=("${@:$i:$array2_len}")
((i += $array2_len))
# You can now read the extra arguments all at once and gather them into a
# new array like this:
extra_args_array=("${@:$i}")
# OR you can read the extra arguments individually into their own variables
# one-by-one like this
extra_arg1="${@:$i:1}"
((i++))
extra_arg2="${@:$i:1}"
((i++))
# Print the output
echo "array1:"
print_one_array "${array1[@]}"
echo "array2:"
print_one_array "${array2[@]}"
echo "extra_arg1 = $extra_arg1"
echo "extra_arg2 = $extra_arg2"
echo "extra_args_array:"
print_one_array "${extra_args_array[@]}"
}
使用示例:
echo "Printing array1 and array2 plus some extra args"
print_two_arrays_plus_extra_args "${#array1[@]}" "${array1[@]}" \
"${#array2[@]}" "${array2[@]}" "hello" "world"
示例输出:
Printing array1 and array2 plus some extra args
array1:
one
two
three
array2:
four
five
six
seven
eight
extra_arg1 = hello
extra_arg2 = world
extra_args_array:
hello
world
引用:
I referenced a lot of my own sample code from my eRCaGuy_hello_world repo here: array_practice.sh array_slicing_demo.sh [my answer on bash array slicing] Unix & Linux: Bash: slice of positional parameters An answer to my question on "How can I create and use a backup copy of all input args ("$@") in bash?" - very useful for general array manipulation of the input argument array An answer to "How to pass array as an argument to a function in Bash", which confirmed to me this really important concept that: You cannot pass an array, you can only pass its elements (i.e. the expanded array).
参见:
[我关于这个主题的另一个答案]如何在Bash中将数组作为参数传递给函数
注:这是我在Stack Overflow上找不到答案后自己发布的粗略的解决方案。它只允许传递一个数组,并且它是参数列表的最后一个元素。实际上,它根本没有传递数组,而是传递数组元素的列表,这些元素被called_function()重新组装成一个数组,但它对我来说是有效的。不久之后,Ken发布了他的解决方案,但我把我的保留在这里作为“历史”参考。
calling_function()
{
variable="a"
array=( "x", "y", "z" )
called_function "${variable}" "${array[@]}"
}
called_function()
{
local_variable="${1}"
shift
local_array=("${@}")
}
这里的基本问题是,设计/实现数组的bash开发人员真的把事情搞砸了。他们认为${array}只是${array[0]}的简称,这是一个严重的错误。特别是当您认为${array[0]}没有意义并且如果数组类型是关联的,则计算结果为空字符串时。
Assigning an array takes the form array=(value1 ... valueN) where value has the syntax [subscript]=string, thereby assigning a value directly to a particular index in the array. This makes it so there can be two types of arrays, numerically indexed and hash indexed (called associative arrays in bash parlance). It also makes it so that you can create sparse numerically indexed arrays. Leaving off the [subscript]= part is short hand for a numerically indexed array, starting with the ordinal index of 0 and incrementing with each new value in the assignment statement.
因此,${array}应该计算为整个数组,索引和所有。它的求值应该是赋值语句的倒数。任何计算机科学专业的三年级学生都应该知道这一点。在这种情况下,这段代码将完全按照你所期望的那样工作:
declare -A foo bar
foo=${bar}
然后,按值将数组传递给函数并将一个数组分配给另一个数组将按照shell语法的其余部分执行。但是因为他们做得不对,赋值操作符=对数组不起作用,并且数组不能通过值传递给函数或子shell或一般的输出(echo ${array}),而没有代码来仔细检查它。
因此,如果做得正确,那么下面的例子将显示数组在bash中的用处可以大大提高:
simple=(first=one second=2 third=3)
echo ${simple}
结果输出应该是:
(first=one second=2 third=3)
然后,数组可以使用赋值操作符,并按值传递给函数甚至其他shell脚本。通过输出到文件很容易存储,也很容易从文件加载到脚本中。
declare -A foo
read foo <file
可惜的是,一个顶级的bash开发团队让我们失望了。
因此,要将数组传递给函数,实际上只有一个选项,那就是使用nameref特性:
function funky() {
local -n ARR
ARR=$1
echo "indexes: ${!ARR[@]}"
echo "values: ${ARR[@]}"
}
declare -A HASH
HASH=([foo]=bar [zoom]=fast)
funky HASH # notice that I'm just passing the word 'HASH' to the function
将导致以下输出:
indexes: foo zoom
values: bar fast
由于这是通过引用传递的,所以也可以在函数中为数组赋值。是的,被引用的数组必须具有全局作用域,但考虑到这是shell脚本,这应该不是太大的问题。要将一个关联或稀疏索引数组按值传递给一个函数,需要将所有索引和值作为单个字符串扔到参数列表中(如果是一个大数组,则不太有用),如下所示:
funky "${!array[*]}" "${array[*]}"
然后在函数内部写一堆代码来重新组装数组。
function aecho {
set "$1[$2]"
echo "${!1}"
}
例子
$ foo=(dog cat bird)
$ aecho foo 1
cat
DevSolar的回答有一点我不理解(也许他有特定的理由这么做,但我想不出一个):他根据位置参数一个元素一个元素地迭代设置数组。
一个更简单的解释是
called_function()
{
...
# do everything like shown by DevSolar
...
# now get a copy of the positional parameters
local_array=("$@")
...
}