Shell脚本--清理指定天数日志文件

以下是一个基本的清理日志文件的脚本示例,可以删除指定目录下超过指定天数的日志文件。

#!/bin/bash

# Specify the directory where the log files are stored
LOG_DIR="/path/to/log/directory"

# Specify the number of days of logs to keep
DAYS_TO_KEEP=7

# Find all log files in the directory that are older than the specified days
find "${LOG_DIR}" -name "*.log" -type f -mtime +"${DAYS_TO_KEEP}" -print0 | while read -d $'\0' FILENAME
do
  # Remove the log file
  rm "${FILENAME}"
  echo "Deleted file: ${FILENAME}"
done

# Optional: compress any remaining log files in the directory
find "${LOG_DIR}" -name "*.log" -type f -exec gzip {} \ ;

# Optional: remove any empty directories in the log directory
find "${LOG_DIR}" -type d -empty -delete

该脚本首先定义了存储日志文件的目录(LOG_DIR)和要保留的日志文件天数(DAYS_TO_KEEP)。然后使用find命令查找在该目录中超过指定天数的所有日志文件。每个找到的日志文件都会被删除,并显示一个消息来指示已删除哪个文件。

此外,还提供了一些可选的操作,例如使用gzip命令压缩剩余的日志文件和删除日志目录中的任何空目录。你可以根据需要添加或删除这些操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值