核心命令解析
find /var/www -type f -mtime +30 -exec rm -f {} \;
| 參數 | 含義 |
/var/www | 目標搜索路徑 |
-type f | 僅匹配普通文件(排除目錄、鏈接、設備文件) |
-mtime +30 | 修改時間超過 30 天(+n 表示 > n*24小時) |
-exec rm -f {} \; | 對每個匹配文件執行刪除,{} 佔位符,\; 結束標記 |
時間參數精確控制
| 參數 | 含義 | 示例 |
-mtime n | 修改時間恰好 n*24h 前 | -mtime 0 今天修改 |
-mtime +n | 修改時間超過 n*24h 前 | -mtime +7 一周前 |
-mtime -n | 修改時間在 n*24h 內 | -mtime -1 24h 內 |
-mmin n | 按分鐘精度 | -mmin +60 1小時前 |
-atime | 訪問時間 | 清理長期未訪問文件 |
-ctime | 狀態改變時間 | 權限/所有者變更時間 |
安全增強版命令
# 1. 先預覽將刪除的文件(生產環境必做)
find /var/www -type f -mtime +30 -ls
# 2. 排除關鍵目錄/文件
find /var/www -type f -mtime +30 \
-not -path "*/.git/*" \
-not -path "*/backup/*" \
-not -name "*.keep" \
-exec rm -f {} \;
# 3. 使用 -delete 內建動作(更高效,避免 fork 開銷)
find /var/www -type f -mtime +30 -delete
# 4. 處理文件名含空格/特殊字符
find /var/www -type f -mtime +30 -print0 | xargs -0 rm -f
crontab 定時任務配置
編輯 crontab
# root 權限編輯
crontab -e
# 或系統級定時任務(推薦)
vim /etc/cron.d/cleanup-expired
標準調度表達式
# 每天凌晨 1:30 執行
30 1 * * * root find /var/www -type f -mtime +30 -delete
# 每週日 2:00 清理臨時文件
0 2 * * 0 root find /tmp -type f -mtime +7 -delete
# 每月 1 號 3:00 清理舊日志
0 3 1 * * root find /var/log -type f -name "*.log.*" -mtime +90 -delete
企業級清理腳本模板
#!/bin/bash
# /usr/local/sbin/cleanup-expired.sh
# 配置文件:/etc/cleanup-expired.conf
CONFIG="/etc/cleanup-expired.conf"
LOG="/var/log/cleanup-expired.log"
log() { echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }
[ -f "$CONFIG" ] || { log "配置文件不存在: $CONFIG"; exit 1; }
while IFS='|' read -r path days exclude_pattern; do
[[ "$path" =~ ^#.*$ ]] && continue
[ -z "$path" ] && continue
log "開始清理: $path (>$days 天)"
CMD="find \"$path\" -type f -mtime +$days"
[ -n "$exclude_pattern" ] && CMD+=" -not -path \"$exclude_pattern\""
CMD+=" -print0 | xargs -0 rm -f"
DELETED=$(eval "$CMD" 2>&1 | wc -l)
log "清理完成,刪除 $DELETED 個文件"
done < "$CONFIG"
配置文件示例
# 路徑|天數|排除模式(可選)
/var/www/html|30|*/.git/*
/var/log/nginx|90|*/archive/*
/tmp|7|
/var/spool/mail|180|
/opt/app/cache|14|*/persistent/*
進階場景:基於文件大小/類型清理
# 清理超過 100MB 的舊文件
find /data -type f -size +100M -mtime +365 -delete
# 僅清理特定擴展名
find /var/www -type f \( -name "*.tmp" -o -name "*.cache" -o -name "*.bak" \) -mtime +7 -delete
# 保留最近 N 個文件(按修改時間)
find /backup -type f -name "*.tar.gz" -printf "%T@ %p\n" | sort -n | head -n -5 | cut -d' ' -f2- | xargs rm -f
監控與告警
# 腳本結尾添加
if [ $DELETED -gt 1000 ]; then
echo "警告:單次刪除 $DELETED 文件,請人工複核" | mail -s "清理異常告警" admin@company.com
fi
# 記錄磁盤空間釋放
df -h /var >> "$LOG"
避坑指南
- 絕對路徑:crontab 中所有命令使用絕對路徑
- 環境變量:腳本開頭聲明
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
- 日誌輪轉:配置
logrotate 管理清理日誌本身
- 測試優先:新增規則先跑
find ... -ls 確認匹配正確
- 權限最小化:專用服務賬號執行,僅賦予目標目錄寫入權