如何将参数 4..99 传递给另一个函数

如何将参数 4..99 传递给另一个函数

我正在调用一个函数,并且希望将最多 100 个参数传递给另一个函数。我不想传递前 3 个参数,我从 param4 开始作为另一个程序的第一个参数。

我目前允许额外传递最多 19 个

$function_under_test "$4" "$5" "$6" "$7" "$8" "$9" "${10}" "${11}" "${12}" 
  "${13}" "${14}" "${15}" "${16}" "${17}" "${18}" "${19}"

但这对于较大的参数集来说并不是很可靠。

我试过

  declare -a pass_on_params
  for ((a=2; a<$#; a++)); do
    pass_on_params+=(${@[a]})  # line 8
  done
  echo "->" $pass_on_params

但我得到

do_test.sh: line 8: ${@[a]}: bad substitution

完整代码是:

do_test () {
  function_under_test=$1
  line_number=$2
  expected="$3"
  param1="$4"
  declare -a pass_on_params
  for ((a=2; a<$#; a++)); do
    pass_on_params+=(${@[a]})
  done
  echo "ppppppppp" $pass_on_params
  $function_under_test "$4" "$5" "$6" "$7" "$8" "$9" "${10}" "${11}" "${12}" "${13}" "${14}" "${15}" "${16}" "${17}" "${18}" "${19}"
  if [ $result -eq $expected ]; then
    printf '.'
  else
    printf 'F'
    error_messages=$error_messages"Call to '$function_under_test $param1' failed: $result was not equal to $expected at line $line_number\n"
  fi
}

外壳是 bash

答案1

"${@:4}"在 bash 中为我工作。您还可以分配给另一个数组并对其进行索引:

foo=("$@")
second_function "${foo[@]:4}"

答案2

只需使用另一个函数:

fn(){
    pass(){
        shift "$shift"
        "$other" "$@"
    }
    other=fn2 shift=3 pass "$@"
    unset -f pass
}

不过,最好以有组织的方式迭代参数。喜欢...

while [ "$#" -gt 0 ]
do    : something with "$1"
shift;done

..或者..

for arg do : something with "$arg"; done

...但很难说清你在做什么。

eval如果正确处理引用,则可以安全地将数学表达式转换为位置参数:

eval "fn2 $(i=3
    until [ "$#" -le 3 ]
    do    printf '"${%d}" ' "$((i+=1))"
    shift;done
)"

答案3

你想移动 3 次并通过 $@

完整代码是:

do_test () {
  function_under_test=$1;shift
  line_number=$1;shift
  expected="$1";shift
  echo "ppppppppp" $@
  $function_under_test "$@"
  if [ $result -eq $expected ]; then
    printf '.'
  else
    printf 'F'
    error_messages=$error_messages"Call to '$function_under_test $param1' failed: $result was not equal to $expected at line $line_number\n"
  fi
}

相关内容