脚本如下:主要功能是,遍历所有的文件,如果是文件,则删除,如果是文件夹,则再次查询遍历
备注:linux一定要注意变量的赋值“=”左右不能有空格
#!/bin/sh
root_paths="/home/static/common"
paths=` ls /home/static/common/ `
rm_report(){
old=` stat -c %Y $1` #%Y 表示最近更新时间 ,1表示获取第一个标量
now=` date +%s `
diff=`expr $now - $old`
if [ $diff -gt 1728000 ];then #17280000s 20天
rm -rf $1
fi
}
for path in ${paths}
do
if [ -d "${root_paths}/${path}" ];then
jacoco_paths=` ls ${root_paths}/${path} `
for jacoco_path in ${jacoco_paths}
do
rm_report "${root_paths}/${path}/${jacoco_path}"
done
else
rm_report "${root_paths}/${path}"
fi
done
增加定时任务:
使用crontab命令:
基本格式 :
* * * * * command
分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令
方法一:
在任何目录下可以新建一个如下脚本
crontest.cron:
0 23 20 * * /bin/sh /home/report_rm.sh >> rm.txt #表示每个月20号23点执行
crontab crotest.cron
备注:但这个会覆盖其他定时任务,不建议这样操作
方法二、
crontab -e 编辑现有任务,新增任务
0 23 20 * * /bin/sh /home/report_rm.sh >> rm.txt #表示每个月20号23点执行
重启crontab 生效
service crond start //启动服务
service crond stop //关闭服务
service crond restart //重启服务
service crond reload //重新载入配置
crontab -l #可以查看执行的任务