LINUX编写脚本定时清除日志

749 阅读1分钟

 先看linux上是否安装crontab如果没有根据以下博客安装:www.cnblogs.com/Alan-Jones/…

脚本内容就是将日志文件大小变为0,因为如果你删除了日志文件或许的日志不会输出也不会有新的日志文件生成,所以我们选择将文件大小变为0

脚本内容:

#!/bin/bash

status(){
  date
  find /opt/ -name '*.opt' -type f -print -exec truncate -s 0 {} ;
  echo "清空log成功"
  return
}

case "$1" in
    status)
        status;;*)
            echo "清除失败"
esac

主要内容就是:

find /opt/ -name '*.opt' -type f -print -exec truncate -s 0 {} ;

意思就是将opt目录下所有后缀为opt的文件大小调整为0

配置脚本权限:

chmod 777 clearopt.sh

配置定时任务:

   基础用法:

   crontab -l    :查看定时任务

   crontab -e    :添加任务

   crontab -r   :删除任务

   cat  /etc/crontab    :查看crontab文件

crontab的时间格式的使用:blog.csdn.net/resilient/a…

执行命令添加一个定时任务:

crontab -e  

内容:

*/1 * * * * /opt/clearopt.sh > /opt/clear.log

先设置1分钟测试一下,没问题了就设置自己想要定义的时间:

1、在 12:01 a.m 运行,即每天凌晨过一分钟
    1 0 * * * /opt/clearopt.sh > /opt/clear.log


2、每个月的第一天 1:10 p.m 运行
    10 13 1 * * /opt/clearopt.sh > /opt/clear.log


3、每个工作日 11 p.m 运行。
    0 23 * * 1-5 /opt/clearopt.sh > /opt/clear.log

也可以直接定时执行命令不需要脚本:

*/1 * * * * find /opt/ -name '*.opt' -type f -print -exec truncate -s 0 {} ;

\