admin管理员组

文章数量:1531307

清理日志文件shell脚本

我们在工作中不免要定时清理一些文件,这里给大家推荐使用shell+crontab实现定时清理日志文件。
shell:shell脚本负责执行命令清理指定文件
crontab:crontab负责定时去执行shell脚本

#!/bin/bash

#find:linux的查找命令,用户查找指定条件的文件;
#/opt/soft/log/:想要进行清理的任意目录;
#-mtime:标准语句写法;
#+3:查找3天前的文件,这里用数字代表天数;
#"*.log":希望查找的数据类型,"*.jpg"表示查找扩展名为jpg的所有文件,"*"表示查找所有文件,这个可以灵活运用,举一反三;
#-exec:固定写法;
#rm -rf:强制删除文件,包括目录;
# {} ; :固定写法,一对大括号+空格++; 

find /root/testlog/ -mtime +3 -name "*.log" -exec rm -rf {} \;

crontab

1、将清理日志的shell脚本放在服务上。根据规定,定一个统一的路径和统一的命名规范。

2、将文件添加到定时任务crontab

crontab -e:编辑当前用户的定时任务
crontab -l:查看当前用户的定时任务
crontab -r:删除当前用户的定时任务

3、脚本样例

#!/bin/bash

find /root/testlog/ -mtime +3 -name "*.log" -exec rm -rf {} \;

4、crontab 任务内容分析

# 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) 
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
0 5 * * 7 /root/programs/render-cluster/scripts/clear_gateway_back.sh

本文标签: 脚本文件Shell