shell 如何将数组作为参数传递给函数

ssgvzors  于 2022-11-16  发布在  Shell
关注(0)|答案(8)|浏览(428)

正如我们所知,在bash编程中传递参数的方式是$1,...,$N。然而,我发现将数组作为参数传递给一个接收多个参数的函数并不容易。下面是一个例子:

f(){
 x=($1)
 y=$2

 for i in "${x[@]}"
 do
  echo $i
 done
 ....
}

a=("jfaldsj jflajds" "LAST")
b=NOEFLDJF

f "${a[@]}" $b
f "${a[*]}" $b

如上所述,函数f接收两个参数:第一个被分配给x,它是一个数组,第二个被分配给y
f有两种调用方式。第一种方式使用"${a[@]}"作为第一个参数,结果为:

jfaldsj 
jflajds

第二种方式使用"${a[*]}"作为第一个参数,结果为:

jfaldsj 
jflajds 
LAST

这两个结果都不是我所希望的。那么,有没有人知道如何在函数之间正确传递数组?

nqwrtyyt

nqwrtyyt1#

不能传递数组,只能传递其元素(即扩展数组)。

#!/bin/bash
function f() {
    a=("$@")
    ((last_idx=${#a[@]} - 1))
    b=${a[last_idx]}
    unset a[last_idx]

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f "${x[@]}" "$b"
echo ===============
f "${x[*]}" "$b"

另一种可能是按名称传递数组:

#!/bin/bash
function f() {
    name=$1[@]
    b=$2
    a=("${!name}")

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f x "$b"
xqnpmsa8

xqnpmsa82#

通过设置-n属性,可以按名称引用将数组传递给bash中的函数(从版本4.3开始):

show_value () # array index
{
    local -n myarray=$1
    local idx=$2
    echo "${myarray[$idx]}"
}

这适用于索引数组:

$ shadock=(ga bu zo meu)
$ show_value shadock 2
zo

它也适用于关联数组:

$ declare -A days=([monday]=eggs [tuesday]=bread [sunday]=jam)
$ show_value days sunday
jam

另请参阅缐上手册中的namerefdeclare -n

dhxwm5r4

dhxwm5r43#

您可以先传递“标量”值,这样会简化事情:

f(){
  b=$1
  shift
  a=("$@")

  for i in "${a[@]}"
  do
    echo $i
  done
  ....
}

a=("jfaldsj jflajds" "LAST")
b=NOEFLDJF

f "$b" "${a[@]}"

此时,您还可以直接使用数组式的位置参数

f(){
  b=$1
  shift

  for i in "$@"   # or simply "for i; do"
  do
    echo $i
  done
  ....
}

f "$b" "${a[@]}"
izj3ouym

izj3ouym4#

这将解决将数组传递给函数的问题:

#!/bin/bash

foo() {
    string=$1
    array=($@)
    echo "array is ${array[@]}"
    echo "array is ${array[1]}"
    return
}
array=( one two three )
foo ${array[@]}
colors=( red green blue )
foo ${colors[@]}
o8x7eapl

o8x7eapl5#

这样试试

function parseArray {
    array=("$@")

    for data in "${array[@]}"
    do
        echo ${data}
    done
}

array=("value" "value1")

parseArray "${array[@]}"
uyhoqukh

uyhoqukh6#

将数组作为函数传递

array() {
    echo "apple pear"
}

printArray() {
    local argArray="${1}"
    local array=($($argArray)) # where the magic happens. careful of the surrounding brackets.
    for arrElement in "${array[@]}"; do
        echo "${arrElement}"
    done

}

printArray array
4szc88ey

4szc88ey7#

下面是一个例子,我在函数中接收了2个bash数组,以及它们后面的附加参数。这种模式可以无限地继续 * 任意数量的bash数组 * 和 * 任意数量的附加参数 *,适应 * 任意输入参数顺序 *,只要每个bash数组的长度正好在该数组元素之前。

print_two_arrays_plus_extra_args的函数定义:

# 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
}

# 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[@]}"
}

示例用法:

array1=()
array1+=("one")
array1+=("two")
array1+=("three")

array2=("four" "five" "six" "seven" "eight")

echo "Printing array1 and array2 plus some extra args"
# Note that `"${#array1[@]}"` is the array length (number of elements
# in the array), and `"${array1[@]}"` is the array (all of the elements
# in the array) 
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

更多的例子和详细的解释,这是如何工作,请参阅我对这个主题的较长的答案在这里:Passing arrays as parameters in bash

9nvpjoqh

9nvpjoqh8#

您还可以创建一个包含数组的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

相关问题