首页 > 解决方案 > Bash:将不同的参数列表传递给函数

问题描述

我使用这个函数将一些文件名提供给另一个命令。

function fun(){  
  find "${@}" -print0 | xargs -r0 other_command
}

调用时,所有参数都传递给以find过滤文件名(-type, -name,等)

有什么方法可以将其中一些论点传递给other_command? 如果可能的话,可变数量的参数。

像这样的东西

fun [list of aguments for find] [list of aguments for other_command]   # pseudo-phantasy syntax

可能吗?

标签: bashshellscriptingargumentsparameter-passing

解决方案


通过“nameref”将几个数组传递给函数。

fun() {
  local -n first_args="$1"
  local -n second_args="$2"
  local -i idx
  for idx in "${!first_args[@]}"; do
    printf 'first arg %d: %s\n' "$idx" "${first_args[idx]}"
  done
  for idx in "${!second_args[@]}"; do
    printf 'second arg %d: %s\n' "$idx" "${second_args[idx]}"
  done
  echo 'All first args:' "${first_args[@]}"
  echo 'All second args:' "${second_args[@]}"
}

one_arg_pack=(--{a..c}{0..2})
another_arg_pack=('blah blah' /some/path --whatever 'a b c')

fun one_arg_pack another_arg_pack

推荐阅读