将多个不同的数组传递给Shell函数 [英] Passing multiple distinct arrays to a shell function

查看:125
本文介绍了将多个不同的数组传递给Shell函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ksh以外的外壳不支持传递引用,因此如何在不使用全局变量的情况下将多个数组传递到bash中的函数中,并以允许将任何合法变量内容包含为数组元素的方式(没有保留的签名)?

Because shells other than ksh do not support pass-by-reference, how can multiple arrays be passed into a function in bash without using global variables, and in a way which allows any legal variable content to be included as an array element (no reserved sigils)?

推荐答案

自bash 4.3起

截至2016年,现代bash支持通过引用传递(也称为nameref属性):

demo_multiple_arrays() {
  local -n _array_one=$1
  local -n _array_two=$2
  printf '1: %q\n' "${_array_one[@]}"
  printf '2: %q\n' "${_array_two[@]}"
}

array_one=( "one argument" "another argument" )
array_two=( "array two part one" "array two part two" )

demo_multiple_arrays array_one array_two

另请参见手册页中的declare -n.

这可以通过使用调用约定来安全地完成,该约定将参数数放在每个数组之前,例如:

This can be done safely by using a calling convention which puts number-of-arguments before each array, as such:

demo_multiple_arrays() {
  declare -i num_args array_num;
  declare -a curr_args;
  while (( $# )) ; do
    curr_args=( )
    num_args=$1; shift
    while (( num_args-- > 0 )) ; do
      curr_args+=( "$1" ); shift
    done
    printf "$((++array_num)): %q\n" "${curr_args[@]}"
  done
}

然后可以这样称呼它:

array_one=( "one argument" "another argument" )
array_two=( "array two part one" "array two part two" )
demo_multiple_arrays \
  "${#array_one[@]}" "${array_one[@]}" \
  "${#array_two[@]}" "${array_two[@]}"

这篇关于将多个不同的数组传递给Shell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆