You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash如何为函数分别传递find与后续命令的两组可变参数

完全可以实现,最通用的方案是约定--作为参数分界符,前面的参数分配给find,后面的参数分配给other_command,既不会和find的原生参数冲突,也支持任意长度的两类参数,同时完全兼容原有调用逻辑。

实现代码

function fun() {
  local find_args=()
  local other_args=()
  local split_flag=0

  # 拆分两类参数
  for arg in "$@"; do
    if [[ $split_flag -eq 0 && $arg == '--' ]]; then
      split_flag=1
      continue
    fi
    (( split_flag == 0 )) && find_args+=("$arg") || other_args+=("$arg")
  done

  find "${find_args[@]}" -print0 | xargs -r0 other_command "${other_args[@]}"
}

调用示例

  • 原有使用习惯完全保留,不需要修改已有调用:
    # 所有参数都传给find,和修改前逻辑完全一致
    fun /var/log -type f -mtime -7 -name "*.log"
    
  • 需要给other_command传参时,用--分隔即可:
    # -- 前的参数给find,后的参数给other_command
    fun /var/log -type f -mtime -7 -name "*.log" -- -q --output=/tmp/scan_result.txt
    

特殊场景适配

如果你需要将匹配到的文件名放在other_command参数的中间位置,而非末尾,可以调整xargs部分的写法,用占位符指定文件名位置:

# 示例:实现 other_command [自定义参数1] 文件名 [自定义参数2] 的调用格式
find "${find_args[@]}" -print0 | xargs -r0 -I {} other_command "${other_args[@]:0:1}" {} "${other_args[@]:1}"

内容的提问来源于stack exchange,提问作者stander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:45:02