Automatically delete logs older than n days

Linux is a system that can automatically generate files, logs, emails, backups, etc. Although hard disks are cheap nowadays, we can have a lot of hard disk space for these files to be wasted, and it is a refreshing thing to let the system regularly clean up some unnecessary files. You don’t need to worry about whether you need to clear the log every day, and you don’t need to receive an alarm message about insufficient hard disk space every day. If you want to rest, let us leave this matter to the machine to execute it regularly.

 

1. Delete file command:

find the corresponding directory -mtime + days -name "file name" -exec rm -rf {} \;

Example command:

find /opt/soft/log/ -mtime +30 -name "*.log" -exec rm -rf {} \;

illustrate:

Delete all files with ".log" 30 days ago in the /opt/ soft /log/ directory . The specific parameters are described as follows:

find: Linux search command, the user finds files with specified conditions ;

/opt/ soft /log/: any directory you want to clean up ;

-mtime: standard statement writing ;

+30: Find files older than 30 days, where numbers represent the number of days ;

"* .log ": The type of data you want to find, "*.jpg" means to find all files with the extension jpg, "*" means to find all files, this can be used flexibly, and inferences from one case to another ;

-exec: fixed spelling ;

rm -rf: Force deletion of files, including directories ;

{} \; : Fixed notation, a pair of braces + space +\+; 

 

2. Schedule tasks:

If you think it is too troublesome to manually execute the statement every time, you can write this small statement into an executable shell script file, and then set cron to schedule execution, then the system can automatically clean up related files.

 

2.1 Create a shell:

touch /opt/soft/bin/auto-del-30-days-ago-log.sh

chmod +x auto-del-30-days-ago-log.sh

Create a new executable file auto-del-30-days-ago-log.sh and assign runnable permissions

 

2.2 Edit the shell script:

vi auto-del-30-days-ago-log.sh

Edit the auto-del-30-days-ago-log.sh file as follows:

 

#!/bin/sh

find /opt/soft/log/ -mtime +30 -name "*.log" -exec rm -rf {} \;

 

ok, save and exit (:wq) .

 

2.3 Scheduled tasks:

#crontab -e

Add the auto-del-30-days-ago-log.sh execution script to the system scheduled task and execute it automatically at the point

enter:

10 0 * * * /opt/soft/log/auto-del-7-days-ago-log.sh >/dev/null 2>&1

The setting here is to execute the auto-del-30-days-ago-log.sh file at 0:10 am every day for data cleaning tasks .

After completing the above three steps, you will no longer worry about whether the hard disk space is full every day. It is time to clean up the log files, and you will no longer receive the alarm message of insufficient hard disk space on the server. Go read a book and drink coffee with confidence!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327092567&siteId=291194637