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

如何在GitHub Actions中获取匹配模式的目录列表并遍历?

问题修复:正确获取并遍历匹配pre-*的目录列表

你的脚本存在两个关键问题,导致无法正确获取目标目录:

  1. 数组遍历语法错误:原脚本中for dir in dirs;只会循环字符串dirs,而非数组中的目录元素,应该使用"${dirs[@]}"来遍历数组所有元素。
  2. 未处理无匹配的情况:当没有目录匹配pre-*时,bash会将通配符字符串test/lambdas/pre-*直接作为数组元素,导致后续判断出错。可以开启nullglob选项,让无匹配时数组为空。

修正后的完整脚本如下:

- name: Run tests in all lambdas
        if: steps.changes.outputs.layers == 'true'
        run: |
          # 开启nullglob,无匹配时通配符返回空
          shopt -s nullglob
          dirs=(test/lambdas/pre-*)
          # 检查数组是否为空
          if [ ${#dirs[@]} -eq 0 ]; then
            echo "No directories matching test/lambdas/pre-* found"
            exit 0
          fi
          # 遍历数组中的每个目录
          for dir in "${dirs[@]}"; do
            echo "Running command in $dir"
            if [ -d "$dir" ]; then
              (
                cd "$dir" &&
                yarn &&
                yarn prettier:check &&
                yarn build:check &&
                yarn test
              ) || echo "An error occurred in $dir"
            fi
          done
          # 关闭nullglob(可选,避免影响后续命令)
          shopt -u nullglob

额外说明:

  • shopt -s nullglob:开启后,当通配符没有匹配到任何文件/目录时,会返回空而非保留通配符本身。
  • ${#dirs[@]}:获取数组的长度,用来判断是否有匹配的目录。
  • "${dirs[@]}":遍历数组时加上双引号,避免目录名包含空格等特殊字符时出现问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:17:37