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

Bash如何验证文件夹为空后执行ls -A,解决通配符报错与冗余处理问题

解决方案

以下提供两种可直接落地的实现,均能同时解决空目录报错、避免匹配FolderA下文件的需求:

方案1:优化原有分目录处理逻辑(适合固定两个子目录的场景)

核心通过开启nullglob选项解决通配符空匹配报错问题:当目录下没有匹配的.txt文件时,通配符会直接展开为空值,不会保留*.txt字符串传入命令导致报错。

# 开启nullglob解决空匹配问题
shopt -s nullglob
# 用数组存匹配结果,兼容带空格的文件名
files_b=("$incoming/$origin/FolderB"/*.txt)
files_c=("$incoming/$origin/FolderC"/*.txt)

# 处理FolderB的文件
if [ ${#files_b[@]} -gt 0 ]; then
    for file in "${files_b[@]}"; do
        # 此处写入FolderB对应操作逻辑
        echo "处理FolderB文件:$file"
    done
else
    echo -e "\033[1;33mWarning: FolderB 无待处理txt文件\033[0m"
fi

# 处理FolderC的文件
if [ ${#files_c[@]} -gt 0 ]; then
    for file in "${files_c[@]}"; do
        # 此处写入FolderC对应操作逻辑
        echo "处理FolderC文件:$file"
    done
else
    echo -e "\033[1;33mWarning: FolderC 无待处理txt文件\033[0m"
fi

# 可选:关闭nullglob,避免影响后续脚本逻辑
shopt -u nullglob

该方案逻辑简单,无额外遍历操作,性能最高,完全不会匹配到FolderA下的文件。

方案2:优化find实现(适合后续可能扩展子目录的场景)

直接指定find的搜索路径为FolderB和FolderC,从根源上避免匹配到FolderA的文件,无需额外过滤逻辑:

base_dir="$incoming/$origin"
# 分别统计两个目录的txt文件数用于空判断
count_b=$(find "$base_dir/FolderB" -maxdepth 1 -type f -name "*.txt" | wc -l)
count_c=$(find "$base_dir/FolderC" -maxdepth 1 -type f -name "*.txt" | wc -l)

# 空目录警告输出
[ "$count_b" -eq 0 ] && echo -e "\033[1;33mWarning: FolderB 无待处理txt文件\033[0m"
[ "$count_c" -eq 0 ] && echo -e "\033[1;33mWarning: FolderC 无待处理txt文件\033[0m"

# 直接搜索两个子目录下的txt文件,不会涉及FolderA根目录
find "$base_dir/FolderB" "$base_dir/FolderC" -maxdepth 1 -type f -name "*.txt" | while IFS= read -r file; do
    dir=$(basename "$(dirname "$file")")
    if [ "$dir" == "FolderB" ]; then
        # 此处写入FolderB对应操作逻辑
        echo "处理FolderB文件:$file"
    elif [ "$dir" == "FolderC" ]; then
        # 此处写入FolderC对应操作逻辑
        echo "处理FolderC文件:$file"
    fi
done

说明:

  • 加-maxdepth 1可避免搜索子目录下的文件,若需要递归处理可以去掉该参数
  • IFS= read -r的写法兼容带空格、特殊字符的文件名,避免解析错误
  • 直接指定搜索路径为两个子目录,不会遍历FolderA下的根文件,无额外性能损耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:00:02