【Shell】删除指定时间之前的文件

时间:2021-02-24 07:57:12

工作需求,要求删除六小时之前的所有备份数据,以免硬盘爆掉

下面给出第一版:

#!/bin/bash

##create log dirPath
declare logDirPath="/home/ipm/shell/log"
if [ ! -d ${logDirPath} ];then
	mkdir ${logDirPath}
fi
declare logFilePath=${logDirPath}"/jiakuandelete.log"
if [ -f ${logFilePath} ];then
	rm -f ${logFilePath}
fi
touch ${logFilePath}
unset logDirPath

##http in data03,others in data04
declare sourceDataDirPath="/data04/dpi/bak/"
declare sourceDataDirNameArray=("dns" "mms" "ftp" "email" "voip" "rtsp" "im" "p2p" "common")
declare startTime=$(date +%Y%m%d%H%M%S)
echo "-----------------execute time:${startTime} start-----------------" >> ${logFilePath}
unset startTime

declare sixHoursAgo=$(date +%Y%m%d%H -d '-6 hours')
echo "sixHoursAgo:"${sixHoursAgo} >> ${logFilePath}
##delete six hours ago data of "http"
echo "deleteDataDirPath:rm -f /data03/dpi/bak/http/*"${sixHoursAgo}"*" >> ${logFilePath}
rm -f /data03/dpi/bak/http/*${sixHoursAgo}*
##delete "dns" "mms" "ftp" "email" "voip" "rtsp" "im" "p2p" "common" datas six hours ago
for sourceDataDirName in ${sourceDataDirNameArray[*]};do
{
	echo "deleteDataDirPath:rm -f "${sourceDataDirPath}${sourceDataDirName}"/*"${sixHoursAgo}"*" >> ${logFilePath}
	rm -f ${sourceDataDirPath}${sourceDataDirName}/*${sixHoursAgo}*
}&
done
wait
declare endTime=$(date +%Y%m%d%H%M%S)
echo "-----------------execute time:${endTime} end-----------------" >> ${logFilePath}
unset endTime
unset logFilePath
unset sourceDataDirName
unset sixHoursAgo
unset sourceDataDirNameArray
unset sourceDataDirPath


公司要求删除一个月之前的备份文件,免得把硬盘给整爆了,上服务器看了下,居然都有3个月的备份没有清理了,还好是sql备份,不然硬盘空间早就满了.


下面是我的解决办法:
cat delbak.sh
1 #!/bin/sh
2 location="/root/sqlbak/"
3 find $location -mtime +30 -type f |xargs rm -f


ps:
location 是设置查找的目录
--mtime +30 是设置时间为30天前
-type f 这周查找的类型为文件

然后加入crontab定时来删除
crontab -l
10 4 1 * * /bin/sh /root/soft_shell/delbak.sh

设定为每个月1号晚上4点10分执行脚本.当然你也可以根据你自己的需求去整.

相同的删除方法:
1 find /root/sqlbak -mtime +30 -type f -name *.gz -exec rm -f {} \;