1. 程式人生 > >【Shell】刪除指定時間之前的檔案

【Shell】刪除指定時間之前的檔案

工作需求,要求刪除六小時之前的所有備份資料,以免硬碟爆掉

下面給出第一版:

#!/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 {} \;