Shell脚本-清理日志
最近业务中常常需要编写一些脚本,故有此文,懒人必备~
#!/bin/bash
# 脚本名称: 清理日志
# 描述: 定时清理日志无用日志
# 版本: 1.0
# 作者: Cikaros
# 邮箱: Cikaros<at>qq.com
# 日期: 2025-07-02
# 版权: (C) 2025 Your Company. All rights reserved.
# === 配置参数 ===
# 默认配置(可被命令行参数覆盖)
keep_days=7
log_tag="cleanup_script"
log_file="/var/log/cleanup.log"
# === 函数定义 ===
check_root_privilege() {
if [ "$EUID" -ne 0 ]; then
log "错误:必须以 root 权限运行此脚本"
exit 1
fi
}
parse_arguments() {
if [[ -n "$1" ]]; then
if [[ "$1" =~ ^[0-9]+$ ]]; then
keep_days="$1"
else
log "错误:保留天数必须为正整数"
exit 1
fi
fi
}
log() {
local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# 写入日志文件
if [[ -d "/var/log" ]]; then
echo "[$timestamp] $message" >> "$log_file"
fi
# 写入系统日志
logger -t "$log_tag" "消息:$message"
}
initialize_logging() {
if [[ ! -f "$log_file" ]]; then
touch "$log_file" 2>/dev/null || {
log "错误:无法创建日志文件 $log_file"
exit 1
}
chmod 644 "$log_file"
fi
}
detect_distro() {
local distro=""
if command -v lsb_release &>/dev/null; then
distro=$(lsb_release -is 2>/dev/null)
elif [[ -f /etc/os-release ]]; then
distro=$(grep ^ID= /etc/os-release | cut -d= -f2)
else
log "警告:无法识别操作系统发行版"
fi
echo "$distro"
}
cleanup_package_cache() {
local distro="$1"
case "$distro" in
Ubuntu|Debian)
log "正在清理 APT 缓存..."
apt clean 2>/dev/null || { log "错误:APT 缓存清理失败"; return 1; }
log "APT 缓存清理完成"
;;
CentOS|Red*Hat)
log "正在清理 YUM 缓存..."
yum clean all 2>/dev/null || { log "错误:YUM 缓存清理失败"; return 1; }
log "YUM 缓存清理完成"
;;
*)
log "警告:不支持的发行版,跳过包管理器缓存清理"
return 0
;;
esac
}
cleanup_old_logs() {
local keep_days="$1"
log "正在清理日志文件..."
# 定义需要保留的关键日志文件路径
local excluded_logs=(
"/var/log/secure"
"/var/log/syslog"
"/var/log/messages"
"/var/log/kern.log"
"/var/log/boot.log"
)
# 构建 find 参数数组
local args=(-type f -name "*.log" -mtime "+${keep_days}" -delete)
for path in "${excluded_logs[@]}"; do
args+=(-not -path "$path")
done
# 执行清理
if find /var/log "${args[@]}" 2>/dev/null; then
log "日志文件清理完成"
return 0
else
log "错误:日志文件清理失败"
return 1
fi
}
# === 主程序 ===
main() {
# 解析命令行参数
parse_arguments "$@"
# 权限检查
check_root_privilege
# 初始化日志
initialize_logging
# 记录开始
log "清理脚本开始执行"
# 检测操作系统发行版
distro=$(detect_distro)
# 清理包管理器缓存
cleanup_package_cache "$distro" || exit 1
# 清理旧日志
cleanup_old_logs "$keep_days" || exit 1
# 记录结束
log "清理脚本执行完毕"
exit 0
}
# === 执行入口 ===
main "$@"
Shell脚本-清理日志
https://blog.cikaros.top/doc/8c796f82.html