Linux automatically deletes n day before logs and instance commands

  • 2020-11-30 08:47:47
  • OfStack

1. Delete file command:

find -mtime + days -name "filename" -exec ES7en-ES8en {} \;

Instance command:


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

Description:

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

find: linux's find command, where the user finds a file with specified criteria;

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

-ES31en: Standard statement writing;

+30: Find the file 30 days ago, where the number represents 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.

-ES41en: Fixed;

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

{} \; : Fixed writing method, 1 pair of braces + space +\+;

2. Planned Tasks:

If it is too much trouble to execute the statement manually each time, you can write this small statement to an executable shell script file, and then set cron schedule to execute, then the system can automatically clean the relevant file.

2.1 Create 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, auto-del-30-days-ES63en-log.sh, and assign runnable permissions

2.2 Edit shell script:


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

Edit auto-ES73en-30-ES74en-ES75en-ES76en. sh file as follows:


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

ok, save exit (:wq).

2.3 Planned Tasks:

#crontab -e

Add the ES90en-ES91en-30-ES92en-ES93en-ES94en. sh execution script to the system scheduling task and execute automatically at the point of arrival

Input:


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

The setting here is to perform the es101EN-del-7-ES103en-ES104en-ES105en.sh file cleanup at 10:10 am every day.

After completing the above 3 steps, you will no longer worry about whether the hard disk space is full, it is time to clean up the log files, no longer receive the server hard disk space is insufficient alarm message, feel free to go to read books and drink coffee!

After each task is added, 1 must remember to restart the crond service, otherwise it will not take effect

The code is as follows:

service crond restart

Create your first Shell script

1. Write a script

a) creates a file with the touch command: touch my_script

b) open the my_script file: vi my_script with the vim editor

c) edit the my_script file with the vim editor as follows:


#!/bin/bash            tell shell What program is used to interpret the script 
#My first script
ls -l .*

2. Allow Shell to execute it

chmod 755 my_script

3. Execute my_script script

./my_script

conclusion


Related articles: