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

Windows Git Bash下find命令问题:指定目录执行命令且不递归子目录

解决Windows Git Bash下find命令的目录查找与执行问题

核心需求

在文件系统上层目录,用find查找包含*.tf文件或.git目录的目标目录,执行指定命令后不再递归搜索该目录的子目录,同时规避-execdir的PATH安全提示,解决-exec cd导致的递归问题。

解决方案1:用-execdir并修复PATH安全提示

Git Bash中-execdir提示PATH不安全,是因为默认PATH包含相对路径(如.)。先临时设置安全的绝对路径PATH,再结合-prune阻止递归:

# 临时设置安全PATH(仅包含绝对路径的系统目录)
export PATH="/usr/bin:/bin:/mingw64/bin:$PATH"

# 查找目标目录、执行命令并跳过子目录
find . -type d \
  \( -exec test -e "{}/*.tf" \; -o -exec test -d "{}/.git" \; \) \
  -execdir your-command-here \; \
  -prune

解决方案2:用-exec替代-execdir(无需修改PATH)

通过bash -c在子shell中切换目录执行命令,同时用-prune阻止递归搜索子目录:

find . -type d \
  \( -exec test -e "{}/*.tf" \; -o -exec test -d "{}/.git" \; \) \
  -exec bash -c 'cd "$1" && your-command-here' _ {} \; \
  -prune

关键参数说明

  • -type d:仅遍历目录
  • \( ... -o ... \):组合两个条件(目录下有*.tf文件 或 存在.git子目录)
  • -prune:找到目标目录后,立即停止递归搜索该目录的子目录
  • bash -c 'cd "$1" && your-command-here' _ {}:通过子shell切换到目标目录执行命令,避免原shell工作目录被修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:17:46