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

Linux Shell脚本如何添加循环检查video.txt内所有文件大小

文件大小检查(File size check)

原有问题脚本

file_path="/home/d-vm/"
cd $file_path
# file_path directory
file=($(cat video.txt | xargs ls -lah | awk '{ print $9}'))
# get name in video.txt --- two files for example VID_141523.mp4 VID_2_141523.mp4
minimumsize=1
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
    echo $file size $actualsize bytes
else
    echo error $file size 0 bytes
fi

已知背景

  • VID_141523.mp4在格式转换过程中损坏,文件大小为0字节
  • 现有脚本运行仅输出error VID_20220709_141523.mp4 size 0 bytes,无法遍历校验全部文件
  • 待检查清单文件video.txt内容如下:
    • VID_141523.mp4
    • VID_2_141523.mp4

改造后脚本(添加循环遍历逻辑)

原有脚本未做循环处理,仅会校验数组内第一个文件,使用while逐行读取文件列表做遍历即可实现全量校验,同时优化了特殊文件名兼容、文件不存在的异常判断逻辑:

file_path="/home/d-vm/"
# 切换目录失败直接退出,避免后续路径错误
cd "$file_path" || exit 1
minimumsize=1

# 逐行读取video.txt中的文件名,兼容含空格的特殊文件名
while IFS= read -r file || [ -n "$file" ]; do
    # 跳过列表中的空行
    [ -z "$file" ] && continue
    # 先判断文件是否存在,避免不存在时统计大小报错
    if [ ! -f "$file" ]; then
        echo "error: $file 不存在,跳过校验"
        continue
    fi
    actualsize=$(wc -c <"$file")
    if [ "$actualsize" -ge "$minimumsize" ]; then
        echo "$file 校验通过,大小 $actualsize 字节"
    else
        echo "error: $file 损坏,大小为 0 字节"
    fi
done < video.txt

不建议通过解析ls命令输出获取文件名,当文件名包含空格、换行符等特殊字符时会出现解析错误,直接读取列表文件的方式兼容性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 04:45:37