CodeFree/4_script/CleanLOG.sh

51 lines
1.3 KiB
Bash
Executable File
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
# 默认值
FILE_DIR="."
FILE_SUFFIXES="log"
# 解析命令行选项
while getopts "d:s:h" opt; do
case $opt in
d)
FILE_DIR=$OPTARG
;;
s)
FILE_SUFFIXES=$OPTARG
;;
h)
echo "$0 用于递归清理指定目录下的非当天日志文件,仅保留当日新生成或修改的日志文件" >&2
echo "[-d 指定要清理的目录路径,默认当前路径]" >&2
echo "[-s 指定后缀名清理对应的日志文件,多个后缀名用逗号隔开,默认后缀名 log]" >&2
exit 0
;;
\?)
echo "无效的选项: -$OPTARG" >&2
exit 1
;;
:)
echo "选项 -$OPTARG 需要一个参数." >&2
exit 1
;;
esac
done
# 检查目录是否存在
if [ ! -d "$FILE_DIR" ]; then
echo "错误:目录 '$FILE_DIR' 不存在。"
exit 1
fi
# 获取今天的日期格式为YYYY-MM-DD
TODAY=$(date +%Y-%m-%d)
# 将逗号分隔的后缀转换为数组
IFS=',' read -r -a SUFFIX_ARRAY <<< "$FILE_SUFFIXES"
# 递归查找并删除非当天的日志文件(仅保留当日新生成或修改的文件)
for SUFFIX in "${SUFFIX_ARRAY[@]}"; do
find "$FILE_DIR" -type f -name "*.$SUFFIX*" ! -newermt "$TODAY" -exec rm -f {} \;
done
echo "已完成清理,仅保留了$TODAY的日志文件"