如何将数组作为实际参数而不是全局变量传递给函数

如何将数组作为实际参数而不是全局变量传递给函数

有没有办法将数组作为其参数之一传递给函数?

目前我有

#!/bin/bash
highest_3 () {
  number_under_test=(${array[@]})
  max_of_3=0
  for ((i = 0; i<$((${#number_under_test[@]}-2)); i++ )) { 
    test=$((number_under_test[i] +
      number_under_test[i+1] +
      number_under_test[i+2]))
    if [ $test -gt $max_of_3 ]; then
      max_of_3=$((number_under_test[i]+
        number_under_test[i+1]+
        number_under_test[i+2]))
      result=$((number_under_test[i]))$((number_under_test[i+1]))$((number_under_test[i+2]))
    fi
  } 
}
array=(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
highest_3
echo result=$result
array=(1 2 3 4 3 2 1)
highest_3
echo result=$result

它只需设置array和使用即可工作array,但是有没有办法传入数组,例如 (1 2 3 4 5 4 3 2 1) 作为实际参数,而不是仅仅设置一个(大概是全局)变量?

更新:我希望能够传递除此数组之外的其他参数

答案1

您始终可以将数组传递给函数并在函数内将其重建为数组:

#!/usr/bin/env bash

foo () {
    ## Read the 1st parameter passed into the new array $_array
    _array=( "$1" )
    ## Do something with it.
    echo "Parameters passed were 1: ${_array[@]}, 2: $2 and 3: $3"

}
## define your array
array=(a 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
## define two other variables
var1="foo"
var2="bar"

## Call your function
foo "$(echo ${array[@]})" $var1 $var2

上面的脚本产生以下输出:

$ a.sh
Parameters passed were 1: a 2 3 4 5 6 7 8 7 6 5 4 3 2 1, 2: foo and 3: bar

答案2

您可以将函数内的参数作为数组读取。然后使用这些参数调用该函数。这样的事情对我有用。

#!/bin/bash

highest_3 () {
number_under_test=("$@")
max_of_3=0
for ((i = 0; i<$((${#number_under_test[@]}-2)); i++ )) { 
 test=$((number_under_test[i] +
  number_under_test[i+1] +
  number_under_test[i+2]))
if [ $test -gt $max_of_3 ]; then
  max_of_3=$((number_under_test[i]+
    number_under_test[i+1]+
    number_under_test[i+2]))
  result=$((number_under_test[i]))$((number_under_test[i+1]))$((number_under_test[i+2]))
fi
} 
echo $result
}

highest_3 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1

# or
array=(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
highest_3 "${array[@]}"

答案3

您只能传递字符串作为参数。但您可以传递数组的名称:

highest_3 () {
  arrayname="$1"
  test -z "$arrayname" && exit 1
  # this doesn't work but that is the idea: echo "${!arrayname[1]}"
  eval echo '"${'$arrayname'[1]}"'
}

相关内容