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

Bash脚本问题:根目录二进制/非二进制文件与目录识别错误

Bash脚本误将子目录识别为非二进制文件的修复方案

需求

编写可在根目录运行的Bash脚本,识别目标目录中的二进制文件、非二进制文件及子目录,并仅输出非二进制项(子目录和非二进制文件)。

问题

当前脚本未区分目录与文件,将非空子目录误识别为非二进制文件;且通过文件是否非空(-s)判断二进制的逻辑完全不可靠,导致文本文件被错误标记为二进制。

原代码

directoryPath="/../checker"
firstLevel='./*'
secondLevel='./*/*'
thirdLevel='./*/*/*'
fourthLevel='./*/*/*/*'

if [[ -d $directoryPath ]];                 
then
    for eachfile in $firstLevel $secondLevel $thirdLevel $fourthLevel
    do
        if [[ -s $eachfile ]];              
        then
            echo "$eachfile This is a binary file"
        else
            echo "$eachfile This is a non-binary file"
        fi
    done
else
    echo "$directoryPath is incorrect"
fi

错误输出

./project/README.txt This is a binary file
./project/src This is a non-binary file
./project/testfile1.txt This is a binary file
./project/src/main This is a non-binary file
./project/src/test This is a non-binary file
./project/src/main/example.jar This is a binary file
./project/src/test/example1.jar This is a binary file

修复思路

  1. 先区分目录与文件:优先判断条目是否为目录,直接标记为子目录,避免和文件混淆。
  2. 用可靠方法识别二进制文件:放弃-s判断,使用file命令分析文件MIME编码,准确区分文本(非二进制)和二进制文件。
  3. 递归遍历替代手动路径:用find命令递归遍历指定深度的条目,替代手动编写四级路径的冗余写法。
  4. 仅输出非二进制项:严格符合需求,跳过二进制文件的输出。

修正后的代码

directoryPath="./checker"

# 检查目标目录是否存在
if [[ ! -d "$directoryPath" ]]; then
    echo "$directoryPath 路径不正确"
    exit 1
fi

# 递归遍历目录(深度1-4级),处理每个条目
find "$directoryPath" -mindepth 1 -maxdepth 4 | while read -r entry; do
    if [[ -d "$entry" ]]; then
        echo "$entry 这是子目录"
    elif [[ -f "$entry" ]]; then
        # 通过MIME编码判断是否为文本类非二进制文件
        if file --mime-encoding "$entry" | grep -qE "text|utf-8|us-ascii"; then
            echo "$entry 这是非二进制文件"
        fi
    fi
done

预期输出

./checker/project/README.txt 这是非二进制文件
./checker/project/src 这是子目录
./checker/project/testfile1.txt 这是非二进制文件
./checker/project/src/main 这是子目录
./checker/project/src/test 这是子目录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:35:36