宝塔面板定时任务目录清理日志-定时检测阈值清理
#!/usr/bin/env bash
#
# 检测 /www/server/cron 目录总占用,超过阈值则清空匹配规则的日志文件内容(不删文件)。
#
# 注意:宝塔该目录下常有「哈希名」无后缀文件,实为计划任务脚本,切勿清空。
#       默认只处理 *.log、nohup.out;若你的日志无后缀,请改 LOG_FIND_OPTS 或下面 find 规则。
#
# 用法:chmod +x clean_baota_cron_logs.sh
#       ./clean_baota_cron_logs.sh
# 可加入 crontab:0 3 * * * /path/to/clean_baota_cron_logs.sh >> /var/log/clean_baota_cron_logs.log 2>&1set -uo pipefailTARGET_DIR="${TARGET_DIR:-/www/server/cron}"
# 阈值:10GiB(按 1024 进制,与 du -sk 一致)
THRESHOLD_KB="${THRESHOLD_KB:-$((10 * 1024 * 1024))}"log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }if [[ ! -d "$TARGET_DIR" ]]; thenlog "目录不存在,退出: $TARGET_DIR"exit 0
fi# 当前目录总占用(KB,与 du 默认一致)
SIZE_KB=$(du -sk "$TARGET_DIR" 2>/dev/null | awk '{print $1}')
if [[ -z "$SIZE_KB" || ! "$SIZE_KB" =~ ^[0-9]+$ ]]; thenlog "无法获取目录大小: $TARGET_DIR"exit 1
filog "目录: $TARGET_DIR  当前占用: ${SIZE_KB} KB  阈值: ${THRESHOLD_KB} KB"if (( SIZE_KB <= THRESHOLD_KB )); thenlog "未超过阈值,不处理。"exit 0
filog "超过阈值,开始清空日志文件内容(保留空文件)…"# 仅匹配常见日志文件名;如需追加规则,在下面 find 中增加 -o -name 'xxx'
emptied=0
while IFS= read -r -d '' f; doif [[ -f "$f" && -w "$f" ]]; then: >"$f"# 若系统有 truncate,也可用: truncate -s 0 -- "$f"emptied=$((emptied + 1))fi
done < <(find "$TARGET_DIR" -type f \( -name '*.log' -o -name 'nohup.out' \) -print0 2>/dev/null)log "已清空 ${emptied} 个文件(*.log / nohup.out)。"
log "完成后占用: $(du -sk "$TARGET_DIR" 2>/dev/null | awk '{print $1}') KB"
exit 0