在 Linux 中使用 Bash 脚本删除早于“X”天的文件/文件夹( 二 )

该脚本将删除 10 天前的文件并通过邮件发送文件夹列表 。
你可以根据需要修改 -mtime X 的值 。另外,请替换你的电子邮箱,而不是用我们的 。
# /opt/script/delete-old-files.sh#!/bin/bashprev_count=0fpath=/var/log/apache/2daygeek_access.*find $fpath -type f -mtime +15 -exec ls -ltrd {} ; > /tmp/file.outfind $fpath -type f -mtime +15 -exec rm -rf {} ;count=$(cat /tmp/file.out | wc -l)if [ "$prev_count" -lt "$count" ] ; thenMESSAGE="/tmp/file1.out"TO="[email protected]"echo "Apache Access log files are deleted older than 20 days" >> $MESSAGEecho "+--------------------------------------------- +" >> $MESSAGEecho "" >> $MESSAGEcat /tmp/file.out | awk '{print $6,$7,$9}' >> $MESSAGEecho "" >> $MESSAGESUBJECT="WARNING: Apache log folders are deleted older than 15 days $(date)"mail -s "$SUBJECT" "$TO" < $MESSAGErm $MESSAGE /tmp/file.outfi给 delete-old-files.sh 设置可执行权限 。
# chmod +x /opt/script/delete-old-files.sh最后添加一个 cronjob 自动化此任务 。它于每天早上 7 点运行 。
# crontab -e0 7 * * * /bin/bash /opt/script/delete-old-folders.sh你将看到类似下面的输出 。
Apache Access log files are deleted older than 20 days+--------------------------------------------------------+Oct 11 /var/log/apache/2daygeek_access.11Oct 12 /var/log/apache/2daygeek_access.12Oct 13 /var/log/apache/2daygeek_access.13Oct 14 /var/log/apache/2daygeek_access.14Oct 15 /var/log/apache/2daygeek_access.15


推荐阅读