Linux日志文件清理脚本:删除指定日期前的日志文件

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

在linux的目录下,每天都会生成”log_20240606_1”、“log_20240606_2”、“log_20240607_1”,这样以“log_日期_编号”构成文件名的日志文件。需要用bash写一个脚本,设置一个日志留存日期的变量,默认为3天,每次运行脚本时需要按照变量,删除指定日期及以前的日志

回答:

你可以编写一个Bash脚本来实现这个功能。以下是一个示例脚本,它会删除指定日期及以前的日志文件。默认情况下,日志文件会保留3天。

#!/bin/bash

# 设置默认的日志留存天数
retention_days=3

# 如果提供了参数,则使用参数作为日志留存天数
if [ ! -z "$1" ]; then
  retention_days=$1
fi

# 获取当前日期
current_date=$(date +%Y%m%d)

# 计算保留日期的阈值
threshold_date=$(date -d "$current_date - $retention_days days" +%Y%m%d)

# 遍历当前目录下的所有日志文件
for file in log_*; do
  # 提取文件名中的日期部分
  file_date=$(echo $file | awk -F'_' '{print $2}')
  
  # 如果文件日期小于等于阈值日期,则删除该文件
  if [ "$file_date" -le "$threshold_date" ]; then
    echo "Deleting $file"
    rm -f "$file"
  fi
done

使用说明

  1. 将上述脚本保存为 cleanup_logs.sh
  2. 给脚本添加执行权限:
    chmod +x cleanup_logs.sh
    
  3. 运行脚本:
    ./cleanup_logs.sh
    
    默认情况下,脚本会保留最近3天的日志文件。如果你想指定不同的保留天数,可以在运行脚本时传递一个参数。例如,要保留最近5天的日志文件,可以运行:
    ./cleanup_logs.sh 5
    

脚本解释

  • retention_days=3:设置默认的日志留存天数为3天。
  • if [ ! -z "$1" ]; then retention_days=$1; fi:如果提供了参数,则使用参数作为日志留存天数。
  • current_date=$(date +%Y%m%d):获取当前日期,格式为YYYYMMDD
  • threshold_date=$(date -d "$current_date - $retention_days days" +%Y%m%d):计算保留日期的阈值。
  • for file in log_*; do:遍历当前目录下的所有日志文件。
  • file_date=$(echo $file | awk -F'_' '{print $2}'):提取文件名中的日期部分。
  • if [ "$file_date" -le "$threshold_date" ]; then rm -f "$file"; fi:如果文件日期小于等于阈值日期,则删除该文件。