要求:根据文件最后修改时间删除清理指定目录下面的文件,并在/var/log/deletelog下面生成按月的删除清理日志
分析:
- 在查找文件时要想不受文件名限制 我们采用文件最后修改时间mtime进行查找,而且还适用于删除过期备份。
- find 目录 -type f 查找文件时会根据换行来输出查找的文件,而我们希望给xargs的参数是按照空格输出的,否则直接结合xargs使用会有一定的影响。(可以增加 -print0 用null来作为边界符号,然后结合xargs -0 来格式化输入)
- 切记在使用find的时候,一定要遵循最小结果集原则;find解析式从左到右,所以我们要确保在最左边的过滤符号能够过滤最大数据
解答:
命令行测试
[root@myhost yuki]# pwd
/yuki
[root@myhost yuki]# ll
total 8
-rw-r--r-- 1 root root 91 Nov 19 16:52 testdel.sh
-rw-r--r-- 1 root root 248 Nov 19 16:52 test.sh
[root@myhost yuki]# find /yuki/ -type f -mtime 0
/yuki/testdel.sh
/yuki/test.sh
[root@myhost yuki]# find /yuki/ -type f -mtime 0 -print0
/yuki/testdel.sh/yuki/test.sh
[root@myhost yuki]# find /yuki/ -type f -mtime 0 -print0 |xargs -0
/yuki/testdel.sh /yuki/test.sh
[root@myhost yuki]# find /yuki/ -type f -mtime 0 -print0 |xargs -0 rm -f
[root@myhost yuki]# echo $?
0
[root@myhost yuki]# ll
total 0
脚本
#!/bin/sh
#source /etc/profile
#define variable
logPath=$1
dayNum=$2
monthFormatTime=`date "+%Y-%m"`
recordLogPath="/var/log"
if [ !-d ${recordLogPath} ];then
mkdir -p ${recordLogPath}
fi
recordClearLog=${recordLogPath}${monthFormatTime}.log
deletLog(){
forwardDayNumParam=$1
#findlog
echo "[`date`] >> [INFO]: start to detele the useless log files" >> ${recordClearLog}
find ${logPath} -type f -mtime $1 -print0 |xargs -0 rm -f
echo "[`date`] >> [INFO]: end deteling the useless log files" >> ${recordClearLog}
}
main(){
if [ -z ${logPath} ];then
echo "[`date`] >> [Error]:logPath is not inited , please give a directory path" >> ${recordClearLog}
return
fi
forwardDayNum=+7
if [ -n ${dayNum} -a ${dayNum} -ge 1 ];then
forwardDayNum=${dayNum}
fi
deletLog ${forwardDayNum}
}
main ${logPath} ${dayNum} ${recordClearLog}