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命令压缩剩余的日志文件和删除日志目录中的任何空目录。你可以根据需要添加或删除这些操作。

你可能感兴趣的:(shell)