Bash嵌套for循环中使用find函数的变量解析问题求助
问题解决:Bash嵌套循环遍历子文件夹文件
错误原因分析
你遇到的$spaces': not a valid identifier错误,以及变量解析问题,都是Bash语法使用不当导致的:
- for循环变量名不能加
$前缀:Bash中循环迭代的变量名直接写名称即可,不需要加$,否则会被当成变量值解析,引发标识符错误。 - 变量赋值语法错误:赋值时变量名不能加
$,且等号与值之间不能有空格,否则Bash会把左侧内容当作命令执行。 - 潜在的空格拆分问题:直接用字符串存储
find结果,若文件名/路径包含空格,会被错误拆分成多个元素。
修正后的基础脚本
# 获取main目录下的一级子文件夹 ApisExternal=$(find main -maxdepth 1 -type d) # 遍历每个子文件夹 for spaces in $ApisExternal do # 获取当前子文件夹下的一级文件,注意赋值语法 ApiSpaces=$(find "$spaces" -maxdepth 1 -type f) # 遍历每个文件并输出 for ApiFixValidationError in $ApiSpaces do echo "$ApiFixValidationError" done done
更安全的版本(支持含空格的路径/文件名)
如果你的文件或文件夹名称包含空格,建议用数组存储结果,避免拆分错误:
# 用数组存储子文件夹,-print0和readarray -d ''配合处理空格 readarray -d '' ApisExternal < <(find main -maxdepth 1 -type d -print0) for spaces in "${ApisExternal[@]}" do # 同样用数组存储文件 readarray -d '' ApiSpaces < <(find "$spaces" -maxdepth 1 -type f -print0) for ApiFixValidationError in "${ApiSpaces[@]}" do echo "$ApiFixValidationError" done done
简化方案:单条find命令完成需求
其实不需要嵌套循环,直接用find的深度参数就能实现你的需求:
find main -mindepth 2 -maxdepth 2 -type f
解释:-mindepth 2 指定从main的子文件夹下的文件开始遍历(main为深度1,子文件夹为深度2),-maxdepth 2 限制只遍历到子文件夹下的一级文件,完全匹配你的目录结构。
内容的提问来源于stack exchange,提问作者Dhaval Patel
相关产品推荐
相关产品推荐

