Linux USES timed tasks to periodically clean up logs 45 days before each week

  • 2020-05-12 06:38:25
  • OfStack

This article focuses on Linux's use of timed tasks to regularly clean up logs 45 days before each week. The server generates large log files every day, so it is necessary to clean up the log files regularly so as not to overload the hard disk with them. At this point, we can write an shell script to clean up the logs that are 45 days old under a path, and then set up a scheduled task to execute this script at a regular time each week.

Clean the log script delOldLogs.sh under a certain path:


[root@prx01 cleanlog]# vim /usr/local/cleanlog/delOldLogs.sh
#!/bin/sh
# Delete the input path under the modified time in 45 Log files from days ago 
find $1 -mtime +45 -name "*log*" -exec rm -f {} \;

This code is easy to understand. It is to clean up the log files that have been modified 45 days ago in the path of parameter 1

The script del_all_OldLogs. sh:


[root@prx01 cleanlog]# vim /usr/local/cleanlog/del_all_OldLogs.sh
#!/bin/bash 
/usr/local/cleanlog/delOldLogs.sh "/home/usr/ewp/logs"
/usr/local/cleanlog/delOldLogs.sh "/home/usr/h5/logs"
/usr/local/cleanlog/delOldLogs.sh "/home/usr/Payment/logs"

Add execution permission to the script:


[root@prx01 cleanlog]# chmod a+x /usr/local/cleanlog/del*.sh

Add timing task:


[root@prx01 cron]# vim /var/spool/cron/root

Add the following:


10 0 * * 6 /usr/local/cleanlog/del_all_OldLogs.sh

Note:

In case of insufficient permissions, a timer task for an root user is set In this code means: a week to six 0:10 execution/usr/local/cleanlog/del_all_OldLogs sh this script

Check the timing task:


[root@app05 logs]# crontab -l

Related articles: