如何在GitHub Actions中获取匹配模式的目录列表并遍历?
问题修复:正确获取并遍历匹配
pre-*的目录列表 你的脚本存在两个关键问题,导致无法正确获取目标目录:
- 数组遍历语法错误:原脚本中
for dir in dirs;只会循环字符串dirs,而非数组中的目录元素,应该使用"${dirs[@]}"来遍历数组所有元素。 - 未处理无匹配的情况:当没有目录匹配
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
相关产品推荐
相关产品推荐

