centos7定时任务删除tomcat日志

1、创建并编写shell脚本文件clear_tomcat_logs.sh,内容如下

#!/bin/sh
find /usr/local/zzxsoft/schedule/logs/ -mtime +2 -type f -name zzx.* -exec rm -f '{}' \;
find /usr/local/zzxsoft/apache-tomcat-service/logs/ -mtime +2 -type f -name zzx.* -exec rm -f '{}' \;
find /usr/local/zzxsoft/apache-tomcat-web/logs/ -mtime +2 -type f -name zzx.* -exec rm -f '{}' \;

保存文件 然后该权限:  chmod 755 clear_tomcat_log.sh

以下对上面find语句的解释:(以第一条shell语句为例)

  /usr/local/zzxsoft/schedule/logs/  --设置查找的目录;
  -mtime +2 --设置时间为2天前;
  -type f --设置查找的类型为文件;
  -name *.sh[ab] --设置文件名称中包含sha或者shb;
  -exec rm -f --查找完毕后执行删除操作;
  '{}'  为操作的内容,此为固定格式;
  \    为转义符;'{}' \中间有个空格,此处不加空格会报错;
  ;   为shell语句结束符,表示与其他语句没有关系,单独执行;
 
PS:我踩过的坑:花了很长时间才解决(如果在系统内vi编辑不会出现此问题)
场景:为了省事我在我的主机Windows上先编辑好的文件用ssh工具上传到线上服务器上,一直报错: find: missing argument to `-exec  和  -bash: ./xxx.sh: /bin/sh^M 
原因:Windows的编辑文件的格式和linux是不一样的
解决方案:通过notepad++编辑后选择 Edit –> EOL Conversion –> UNIX/OSX Format  保存后再上传即可
 
2、设置定时任务
   crontab -e  打开编辑定时任务,添加如下内容  
HRLL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

# 每天凌晨6点自动清理tomcat日志信息
00 6 * * * /usr/local/zzxsoft/clear_tomcat_logs.sh

保存后重启定时任务 service crond restart

如果没有安装crond.service会报错:crontab: unrecognized service  需要yum安装一下:yum -y install vixie-cron  即可结局

才疏学浅,如有错误,欢迎指正,谢谢

posted @ 2020-08-18 10:30  众星捧月  阅读(793)  评论(1编辑  收藏  举报