如何将数组作为参数传递给bash函数?
注意:在Stack Overflow上找不到答案后,我自己发布了一个有点粗糙的解决方案。它只允许传递一个数组,并且它是参数列表的最后一个元素。实际上,它根本没有传递数组,而是传递数组元素的列表,这些元素被called_function()重新组装成一个数组,但它对我来说是有效的。如果有人知道更好的方法,请在这里添加。
如何将数组作为参数传递给bash函数?
注意:在Stack Overflow上找不到答案后,我自己发布了一个有点粗糙的解决方案。它只允许传递一个数组,并且它是参数列表的最后一个元素。实际上,它根本没有传递数组,而是传递数组元素的列表,这些元素被called_function()重新组装成一个数组,但它对我来说是有效的。如果有人知道更好的方法,请在这里添加。
注:这是我在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=("${@}")
}
DevSolar的回答有一点我不理解(也许他有特定的理由这么做,但我想不出一个):他根据位置参数一个元素一个元素地迭代设置数组。
一个更简单的解释是
called_function()
{
...
# do everything like shown by DevSolar
...
# now get a copy of the positional parameters
local_array=("$@")
...
}
你可以像这样传递多个数组作为参数:
takes_ary_as_arg()
{
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
declare -a argAry2=("${!2}")
echo "${argAry2[@]}"
}
try_with_local_arys()
{
# array variables could have local scope
local descTable=(
"sli4-iread"
"sli4-iwrite"
"sli3-iread"
"sli3-iwrite"
)
local optsTable=(
"--msix --iread"
"--msix --iwrite"
"--msi --iread"
"--msi --iwrite"
)
takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys
将回声:
sli4-iread sli4-iwrite sli3-iread sli3-iwrite
--msix --iread --msix --iwrite --msi --iread --msi --iwrite
编辑/注释:(摘自下面的评论)
descTable和optsTable作为名称传递,并在函数中展开。因此,在作为参数给出时不需要$。 注意,即使用local定义了descTable等,这仍然有效,因为locals对于它们调用的函数是可见的。 !在$ {!1}展开arg 1变量。 声明-a只是使索引数组显式,这不是严格必要的。
这条即使有空格也适用:
format="\t%2s - %s\n"
function doAction
{
local_array=("$@")
for (( i = 0 ; i < ${#local_array[@]} ; i++ ))
do
printf "${format}" $i "${local_array[$i]}"
done
echo -n "Choose: "
option=""
read -n1 option
echo ${local_array[option]}
return
}
#the call:
doAction "${tools[@]}"
评论Ken Bertelson的解决方案并回答Jan Hettich:
它是如何工作的
try_with_local_arys()函数中的takes_ary_as_arg descTable[@] optsTable[@]行发送:
This is actually creates a copy of the descTable and optsTable arrays which are accessible to the takes_ary_as_arg function. takes_ary_as_arg() function receives descTable[@] and optsTable[@] as strings, that means $1 == descTable[@] and $2 == optsTable[@]. in the beginning of takes_ary_as_arg() function it uses ${!parameter} syntax, which is called indirect reference or sometimes double referenced, this means that instead of using $1's value, we use the value of the expanded value of $1, example: baba=booba variable=baba echo ${variable} # baba echo ${!variable} # booba likewise for $2. putting this in argAry1=("${!1}") creates argAry1 as an array (the brackets following =) with the expanded descTable[@], just like writing there argAry1=("${descTable[@]}") directly. the declare there is not required.
注意:值得一提的是,使用这个括号形式的数组初始化根据IFS或内部字段分隔符初始化新数组,默认为制表符、换行符和空格。在这种情况下,因为它使用[@]符号,所以每个元素都被看作是被引用的(与[*]相反)。
我对它的预订
在BASH中,局部变量作用域是当前函数和从它调用的每个子函数,这转化为这样一个事实,takes_ary_as_arg()函数“看到”那些descTable[@]和optsTable[@]数组,因此它是工作的(见上述解释)。
既然如此,为什么不直接看看这些变量本身呢?这就像写在这里:
argAry1=("${descTable[@]}")
参见上面的解释,它只是根据当前的IFS复制descTable[@]数组的值。
总之
从本质上讲,这只是过去,没有任何价值——和往常一样。
我还想强调Dennis Williamson上面的评论:稀疏数组(没有所有键定义的数组-其中有“孔”)不会像预期的那样工作-我们会失去键并“压缩”数组。
话虽如此,我确实看到了泛化的价值,因此函数可以在不知道名称的情况下获得数组(或副本):
对于~“拷贝”:这个技术已经足够好了,只是需要注意,索引(键)已经没有了。 对于真实副本: 我们可以对键使用eval,例如: Eval本地键=(\${!$1})
然后循环使用它们来创建副本。 注:这里!不是使用它之前的间接/双重求值,而是在数组上下文中返回数组下标(键)。
当然,如果我们要传递descTable和optsTable字符串(不带[@]),我们可以在eval中使用数组本身(如通过引用)。用于接受数组的泛型函数。
function aecho {
set "$1[$2]"
echo "${!1}"
}
例子
$ foo=(dog cat bird)
$ aecho foo 1
cat
这里的基本问题是,设计/实现数组的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[*]}"
然后在函数内部写一堆代码来重新组装数组。
通过一些技巧,您实际上可以将命名参数与数组一起传递给函数。
我开发的方法允许你访问传递给函数的参数,就像这样:
testPassingParams() {
@var hello
l=4 @array anArrayWithFourElements
l=2 @array anotherArrayWithTwo
@var anotherSingle
@reference table # references only work in bash >=4.3
@params anArrayOfVariedSize
test "$hello" = "$1" && echo correct
#
test "${anArrayWithFourElements[0]}" = "$2" && echo correct
test "${anArrayWithFourElements[1]}" = "$3" && echo correct
test "${anArrayWithFourElements[2]}" = "$4" && echo correct
# etc...
#
test "${anotherArrayWithTwo[0]}" = "$6" && echo correct
test "${anotherArrayWithTwo[1]}" = "$7" && echo correct
#
test "$anotherSingle" = "$8" && echo correct
#
test "${table[test]}" = "works"
table[inside]="adding a new value"
#
# I'm using * just in this example:
test "${anArrayOfVariedSize[*]}" = "${*:10}" && echo correct
}
fourElements=( a1 a2 "a3 with spaces" a4 )
twoElements=( b1 b2 )
declare -A assocArray
assocArray[test]="works"
testPassingParams "first" "${fourElements[@]}" "${twoElements[@]}" "single with spaces" assocArray "and more... " "even more..."
test "${assocArray[inside]}" = "adding a new value"
换句话说,您不仅可以通过名称调用参数(这使核心更具可读性),还可以实际传递数组(以及对变量的引用——该特性仅在bash 4.3中有效)!另外,映射的变量都在局部作用域中,就像$1(和其他变量)一样。
实现这一功能的代码非常简单,并且可以在bash 3和bash 4中工作(这是我测试过的唯一版本)。如果你对更多这样的技巧感兴趣,可以让bash开发变得更好更简单,你可以看看我的bash Infinity Framework,下面的代码就是为此目的而开发的。
Function.AssignParamLocally() {
local commandWithArgs=( $1 )
local command="${commandWithArgs[0]}"
shift
if [[ "$command" == "trap" || "$command" == "l="* || "$command" == "_type="* ]]
then
paramNo+=-1
return 0
fi
if [[ "$command" != "local" ]]
then
assignNormalCodeStarted=true
fi
local varDeclaration="${commandWithArgs[1]}"
if [[ $varDeclaration == '-n' ]]
then
varDeclaration="${commandWithArgs[2]}"
fi
local varName="${varDeclaration%%=*}"
# var value is only important if making an object later on from it
local varValue="${varDeclaration#*=}"
if [[ ! -z $assignVarType ]]
then
local previousParamNo=$(expr $paramNo - 1)
if [[ "$assignVarType" == "array" ]]
then
# passing array:
execute="$assignVarName=( \"\${@:$previousParamNo:$assignArrLength}\" )"
eval "$execute"
paramNo+=$(expr $assignArrLength - 1)
unset assignArrLength
elif [[ "$assignVarType" == "params" ]]
then
execute="$assignVarName=( \"\${@:$previousParamNo}\" )"
eval "$execute"
elif [[ "$assignVarType" == "reference" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
elif [[ ! -z "${!previousParamNo}" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
fi
fi
assignVarType="$__capture_type"
assignVarName="$varName"
assignArrLength="$__capture_arrLength"
}
Function.CaptureParams() {
__capture_type="$_type"
__capture_arrLength="$l"
}
alias @trapAssign='Function.CaptureParams; trap "declare -i \"paramNo+=1\"; Function.AssignParamLocally \"\$BASH_COMMAND\" \"\$@\"; [[ \$assignNormalCodeStarted = true ]] && trap - DEBUG && unset assignVarType && unset assignVarName && unset assignNormalCodeStarted && unset paramNo" DEBUG; '
alias @param='@trapAssign local'
alias @reference='_type=reference @trapAssign local -n'
alias @var='_type=var @param'
alias @params='_type=params @param'
alias @array='_type=array @param'
传递几个数组作为参数的一个简单方法是使用字符分隔的字符串。你可以这样调用你的脚本:
./myScript.sh "value1;value2;value3" "somethingElse" "value4;value5" "anotherOne"
然后,你可以像这样在你的代码中提取它:
myArray=$1
IFS=';' read -a myArray <<< "$myArray"
myOtherArray=$3
IFS=';' read -a myOtherArray <<< "$myOtherArray"
通过这种方式,你实际上可以传递多个数组作为参数,它不必是最后一个参数。
要求:在数组中查找字符串的函数。 这是DevSolar解决方案的一个轻微简化,因为它使用传入的参数而不是复制它们。
myarray=('foobar' 'foxbat')
function isInArray() {
local item=$1
shift
for one in $@; do
if [ $one = $item ]; then
return 0 # found
fi
done
return 1 # not found
}
var='foobar'
if isInArray $var ${myarray[@]}; then
echo "$var found in array"
else
echo "$var not found in array"
fi
只是添加到接受的答案,因为我发现如果数组内容是这样的,它就不能很好地工作:
RUN_COMMANDS=(
"command1 param1... paramN"
"command2 param1... paramN"
)
在这种情况下,数组的每个成员都被分割,所以函数看到的数组等价于:
RUN_COMMANDS=(
"command1"
"param1"
...
"command2"
...
)
为了让这种情况工作,我发现的方法是将变量名传递给函数,然后使用eval:
function () {
eval 'COMMANDS=( "${'"$1"'[@]}" )'
for COMMAND in "${COMMANDS[@]}"; do
echo $COMMAND
done
}
function RUN_COMMANDS
只是我的2©
尽管它很丑,但这里有一个变通方法,只要你没有显式地传递一个数组,而是一个对应于数组的变量:
function passarray()
{
eval array_internally=("$(echo '${'$1'[@]}')")
# access array now via array_internally
echo "${array_internally[@]}"
#...
}
array=(0 1 2 3 4 5)
passarray array # echo's (0 1 2 3 4 5) as expected
我相信有人可以提出一个更清晰的思想实现,但我发现这是一个更好的解决方案,而不是传递一个数组作为“{array[@]”},然后在内部使用array_inside=(“$@”)访问它。当存在其他位置/getopts参数时,这就变得复杂了。在这些情况下,我必须首先确定,然后使用shift和数组元素删除的某种组合来删除与数组不关联的参数。
纯粹主义者可能会认为这种方法违反了语言,但从实用主义的角度来说,这种方法为我省去了很多痛苦。在一个相关的主题中,我还使用eval将一个内部构造的数组赋值给一个根据我传递给函数的参数target_varname命名的变量:
eval target_varname =美元”($ {array_inside[@]})”
希望这能帮助到一些人。
我的简短回答是:
function display_two_array {
local arr1=$1
local arr2=$2
for i in $arr1
do
echo "arrary1: $i"
done
for i in $arr2
do
echo "arrary2: $i"
done
}
test_array=(1 2 3 4 5)
test_array2=(7 8 9 10 11)
display_two_array "${test_array[*]}" "${test_array2[*]}"
需要注意的是${test_array[*]}和${test_array2[*]}应该被""包围,否则就会失败。
下面的答案向您展示了如何通过序列化和反序列化将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中将数组作为参数传递给函数
现代bash(显然是4.3或更高版本)允许通过引用传递数组。我将在下面展示。如果您希望手动序列化和反序列化数组,请参阅我在这里对bash常规“索引”数组和bash关联数组的回答。但是,如下所示,通过引用传递数组要简单得多,也更简洁,所以我现在推荐这样做。
下面的代码也可以在我的eRCaGuy_hello_world repo中在线获得:array_pass_as_bash_parameter_by_reference.sh。另请参阅这里的示例:array_pass_as_bash_parameter_2_associate .sh。
下面是一个常规bash数组的演示:
function foo {
# declare a local **reference variable** (hence `-n`) named `data_ref`
# which is a reference to the value stored in the first parameter
# passed in
local -n data_ref="$1"
echo "${data_ref[0]}"
echo "${data_ref[1]}"
}
# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"
样例输出:
摩登原始人 巴尼废墟
...下面是一个关联bash数组的演示(例如:bash哈希表,“字典”或“无序映射”):
function foo {
# declare a local **reference variable** (hence `-n`) named `data_ref`
# which is a reference to the value stored in the first parameter
# passed in
local -n data_ref="$1"
echo "${data_ref["a"]}"
echo "${data_ref["b"]}"
}
# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"
样例输出:
摩登原始人 巴尼废墟
引用:
我从@Todd Lehman的回答中修改了上面的代码示例:如何在Bash中将关联数组作为参数传递给函数? 请参见我的手动序列化/反序列化答案 并在这里查看我的后续问题:为什么man bash页面声明declare和local -n属性“不能应用于数组变量”,但它可以?
你也可以用数组创建一个json文件,然后用jq解析这个json文件
例如:
my-array.json:
{
"array": ["item1","item2"]
}
script.sh:
ARRAY=$(jq -r '."array"' $1 | tr -d '[],"')
然后像这样调用脚本:
script.sh ./path-to-json/my-array.json
您可以在这个类似的问题中找到更多的想法:如何将数组作为参数传递给Bash中的函数