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

Bash脚本中[ -s ]判断0字节空文件返回true的问题求助

Bash脚本异常判断问题解决方案

核心错误原因

  • 文件名不匹配:你实际写入内容的文件是/tmp/tmp_direc_last_update.log,但if判断中检测的是/tmp/tmp_direc_update.log,缺少last字段,检测的是完全无关的文件,自然判断结果不符合预期
  • echo语句语法错误:你写的echo "$file_output > /tmp/tmp_direc_last_update.log右侧缺少闭合双引号,导致重定向符号>被识别为字符串内容的一部分,没有实际将变量值写入目标文件

优化后完整代码

#!/bin/bash
date_time=$(date +%s)
# 替换ls|grep写法,直接筛选/data下权限777、名称为纯数字的目录,输出格式和原有逻辑一致
file_output=$(find /data -maxdepth 1 -type d -perm 777 -regextype posix-extended -regex '.*/[0-9]+$' -printf "%TY-%Tm-%Td %TH:%TM,%f,\n")

rm -rf /tmp/tmp_direc_last_update.log
# 修正引号闭合,正确写入文件
echo "$file_output" > /tmp/tmp_direc_last_update.log

# 修正判断的文件名,和写入的文件保持一致
if [ -s /tmp/tmp_direc_last_update.log ]
then
   sed -e "s/$/$date_time,/" -i /tmp/tmp_direc_last_update.log
   final_file=$(cat /tmp/tmp_direc_last_update.log) 
   echo "$final_file" > /data/stats/direc_last_update.log
else
   exit
fi

补充说明

如果你需要保留原来的ls解析逻辑,仅修正上述两个语法错误即可:补全echo语句的闭合引号、修改if判断的文件名和实际写入的文件一致,就能解决空文件判断失效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:36:00