wei/sh/xz_log_all.sh
2026-06-26 10:10:40 +08:00

98 lines
3.0 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# 功能:扫描 /home/system 下所有包含指定年份日志的目录,列出确认再打包
# 删除功能在74 75 行
# 用法:./xz_log_all.sh <年份> 例如:./xz_log_all.sh 2025
set -u
if [ $# -ne 1 ]; then
echo "错误:请指定年份,例如 ./xz_log_all.sh 2025"
exit 1
fi
year="$1"
if ! [[ "$year" =~ ^[0-9]{4}$ ]]; then
echo "错误:年份格式不正确,应为四位数字"
exit 1
fi
# 临时文件
dir_all=$(mktemp)
dir_target=$(mktemp)
trap "rm -f $dir_all $dir_target" EXIT
echo "正在扫描 /home/system 下的日志目录..."
find /home/system -type f -name "*.log" -printf "%h\n" 2>/dev/null | sort -u > "$dir_all"
echo "正在检查各目录中是否存在 ${year} 年的日志文件..."
while IFS= read -r dir; do
[ -d "$dir" ] || continue
if find "$dir" -maxdepth 1 -type f -name "*$year*.log" -printf "%f\n" 2>/dev/null | grep -q .; then
echo "$dir" >> "$dir_target"
fi
done < "$dir_all"
if [ ! -s "$dir_target" ]; then
echo "未找到任何包含 ${year} 年日志的目录,退出。"
exit 0
fi
echo "找到以下 ${year} 年日志所在的目录(共 $(wc -l < "$dir_target") 个):"
cat -n "$dir_target" | sed 's/^/ /'
read -p "是否开始打包这些目录中的 ${year} 年日志?(y/N) " -r confirm
if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
echo "操作已取消。"
exit 0
fi
success_count=0
fail_count=0
total=$(wc -l < "$dir_target")
echo "开始打包(共 $total 个目录)..."
# 循环读取目录列表
while IFS= read -r dir; do
current=$((success_count + fail_count + 1))
echo "[$current/$total] 正在处理目录:$dir"
# 使用子shell处理避免影响父shell环境并重定向 stdin 以防干扰
(
cd "$dir" < /dev/null || exit 1
# 统计文件数量
file_count=$(find . -maxdepth 1 -type f -name "*$year*.log" -printf "%f\n" 2>/dev/null | wc -l)
if [ "$file_count" -eq 0 ]; then
echo " 目录中没有 $year 年的日志文件,跳过"
exit 0
fi
echo " 找到 $file_count 个文件,正在压缩..."
# 打包压缩(直接管道传递 null 分隔的文件名)
if find . -maxdepth 1 -type f -name "*$year*.log" -printf "%f\0" | tar --null -c -T - | xz -9 > "${year}.tar.xz"; then
echo " ✓ 已生成 ${year}.tar.xz"
# 如需删除原始文件,取消下面注释
find . -maxdepth 1 -type f -name "*$year*.log" -delete
echo " 已删除原始文件"
exit 0
else
echo " ✗ 打包失败 $dir" >&2
exit 1
fi
)
# 根据子shell退出码统计成功/失败
if [ $? -eq 0 ]; then
((success_count++))
else
((fail_count++))
fi
done < "$dir_target"
echo "完成!成功: $success_count, 失败: $fail_count"
if [ $fail_count -gt 0 ]; then
echo "请检查失败的目录。"
fi
echo "如需删除原始日志文件可进入对应目录手动执行rm -f *${year}*.log"
echo "当前已启用删除原始文件"