【问题标题】:Bash: passing different lists of arguments to a functionBash:将不同的参数列表传递给函数
【发布时间】:2021-12-15 09:09:30
【问题描述】:

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

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

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

有没有办法将其中一些参数传递给 other_command ? 尽可能多的参数。

类似的东西

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

有可能吗?

【问题讨论】:

  • 在每一种允许将变量参数传递给函数的语言中,都有两个常见的约束:1) 变量参数必须在位置参数的最后或之后。 2)只能有一组/类型的变量参数。当需要一个函数来处理两个或多个条目列表时;您通常通过引用而不是值传递这些。见Andrej's answer
  • 是的,这回答了我的问题。我设法构造了一个包含 find 和 grep 的字符串,每个字符串都有从 2 数组中获取的自己的参数,并使用 eval 将其弹出: cmdLine="find $paramFirst -print0 | xargs -r0 grep $paramSecond" eval $cmdLine但正如我们所知,eva 是不安全的,到目前为止我还没有找到使其安全的方法
  • 我已经尝试了stackoverflow.com/a/52538533/17281195 的解决方案,但它在这里无法工作,因为“find”是在 token_quote 中执行的。并且管道字符不能被引用。

标签: bash shell scripting arguments parameter-passing


【解决方案1】:

通过“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

【讨论】:

    猜你喜欢
    • 2021-10-05
    • 1970-01-01
    • 2012-04-21
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多