本文介绍在Linux中删除早于“X”天的文件夹的Bash脚本、及使用Bash脚本删除Linux中“X”日之前的文件。
1、Bash脚本:在Linux中删除早于“X”天的文件夹
我们有一个名为“/var/log/app/”的文件夹,其中包含15天的日志,我们将删除10天的旧文件夹,以下为示例:
$ ls -lh /var/log/app/
该脚本将删除10天的旧文件夹,并通过邮件发送文件夹列表。
Bash脚本如下,您可以根据需要更改值“-mtime X”,另外,请替换您的电子邮件ID,而不是我们。
# /opt/script/delete-old-folders.sh
#!/bin/bash
prev_count=0
fpath=/var/log/app/app_log.*
find $fpath -type d -mtime +10 -exec ls -ltrh {} \; > /tmp/folder.out
find $fpath -type d -mtime +10 -exec rm -rf {} \;
count=$(cat /tmp/folder.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="249562751@qq.com"
echo "Application log folders are deleted older than 15 days" >> $MESSAGE
echo "+--------------------------------+" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/folder.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log files are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/folder.out
fi
为“delete-old-folders.sh”文件设置可执行权限:
# chmod +x /opt/script/delete-old-folders.sh
最后添加一个cronjob以使其自动化,它每天早上7点运行:
# crontab -e
0 7 * * * /bin/bash /opt/script/delete-old-folders.sh
您将得到类似下面的输出信息:
2、Bash脚本:删除Linux中“X”日之前的文件
我们有一个名为“/var/log/apache/”的文件夹,其中包含15天的日志,我们将删除10天的旧文件:
# ls -lh /var/log/apache/
该脚本将删除10天的旧文件并通过邮件发送文件夹列表。
Bash脚本如下,您可以根据需要更改值“-mtime X”,另外,请替换您的电子邮件ID,而不是我们。
# /opt/script/delete-old-files.sh
#!/bin/bash
prev_count=0
fpath=/var/log/apache/2daygeek_access.*
find $fpath -type f -mtime +15 -exec ls -ltrd {} \; > /tmp/file.out
find $fpath -type f -mtime +15 -exec rm -rf {} \;
count=$(cat /tmp/file.out | wc -l)
if [ "$prev_count" -lt "$count" ] ; then
MESSAGE="/tmp/file1.out"
TO="249562751@qq.com"
echo "Apache Access log files are deleted older than 20 days" >> $MESSAGE
echo "+--------------------------------+" >> $MESSAGE
echo "" >> $MESSAGE
cat /tmp/file.out | awk '{print $6,$7,$9}' >> $MESSAGE
echo "" >> $MESSAGE
SUBJECT="WARNING: Apache log folders are deleted older than 15 days $(date)"
mail -s "$SUBJECT" "$TO" < $MESSAGE
rm $MESSAGE /tmp/file.out
fi
将可执行权限设置为“delete-old-files.sh”文件:
# chmod +x /opt/script/delete-old-files.sh
最后添加一个cronjob以使其自动化,它每天早上7点运行:
# crontab -e
0 7 * * * /bin/bash /opt/script/delete-old-folders.sh
您将得到类似下面的输出信息:
相关主题