Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 自動清理 N 天前備份腳本與 crontab 定時任務實戰

編輯:Linux 教學

備份文件隨時間增長會佔用大量磁盤空間,結合 find 的 -mtime 與 -exec 實現自動清理,配合 crontab 定時執行,構建零維護備份保留策略。

核心清理命令

find 目標目錄 -mtime +天數 -name "匹配模式" -exec rm -rf {} \;

參數解析

參數含義
-mtime +30查找修改時間超過 30 天的文件(+ 表示大於)
-name "*.*"匹配所有帶擴展名文件,可改為 "*.log"、"backup_*" 等
-exec rm -rf {} \;對每個結果執行強制刪除,{} 佔位符代表文件路徑

實戰腳本創建

#!/bin/bash
# AutoDelBackup.sh
find /root/Backup -mtime +30 -name "*.*" -exec rm -rf {} \;

crontab 定時調度

# 編輯當前用戶定時任務
crontab -e
# 每天凌晨 2 點執行
0 2 * * * /root/AutoDelBackup.sh

進階變體

  • 按創建時間清理:使用 -ctime 替代 -mtime
  • 刪除空目錄:find /backup -type d -empty -delete
  • 保留最近 N 個備份:
    ls -t /backup/*.tar.gz | tail -n +6 | xargs rm -f
  • 日誌記錄:
    find /backup -mtime +30 -name "*.tar.gz" -exec rm -vf {} \; >> /var/log/cleanup.log 2>&1

注意事項

  1. 腳本需可執行權限:chmod +x AutoDelBackup.sh
  2. 路徑建議使用絕對路徑
  3. 生產環境建議先加 -print 測試:find /backup -mtime +30 -print
  4. 大量文件刪除時考慮 ionice -c3 降低 I/O 優先級
Copyright © Windows教程網 All Rights Reserved