feat(database-dump-cleanup): 添加数据库备份文件清理脚本

This commit is contained in:
严浩
2025-09-24 11:30:42 +08:00
parent 7af4a5efef
commit a68ffd2f8c
2 changed files with 121 additions and 0 deletions

115
database-dump-cleanup.sh Executable file
View File

@@ -0,0 +1,115 @@
#!/bin/sh
set -eu
# Remove dump files with a given prefix while keeping the most recent N days (default 7).
PROG=${0##*/}
usage() {
cat <<USAGE
Usage: $PROG --prefix=NAME [--dir=DIR] [--days=N]
--prefix=NAME Filename prefix to match (required).
--dir=DIR Directory to scan (default: current directory).
--days=N Retention window in days (default: 7).
--help Show this help text.
USAGE
}
error() {
printf '%s: %s\n' "$PROG" "$1" >&2
}
die_with_usage() {
error "$1"
usage >&2
exit 1
}
PREFIX=""
TARGET_DIR="."
RETENTION_DAYS=7
while [ "$#" -gt 0 ]; do
case $1 in
--prefix=*)
PREFIX="${1#*=}"
;;
--prefix)
shift
[ "$#" -gt 0 ] || die_with_usage 'Missing value for --prefix'
PREFIX="$1"
;;
--dir=*)
TARGET_DIR="${1#*=}"
;;
--dir)
shift
[ "$#" -gt 0 ] || die_with_usage 'Missing value for --dir'
TARGET_DIR="$1"
;;
--days=*)
RETENTION_DAYS="${1#*=}"
;;
--days)
shift
[ "$#" -gt 0 ] || die_with_usage 'Missing value for --days'
RETENTION_DAYS="$1"
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
-*)
die_with_usage "Unknown option: $1"
;;
*)
if [ -z "$PREFIX" ]; then
PREFIX="$1"
else
die_with_usage "Unexpected positional argument: $1"
fi
;;
esac
shift
done
if [ -z "$PREFIX" ] && [ "$#" -gt 0 ]; then
PREFIX="$1"
shift
fi
if [ -z "$PREFIX" ]; then
die_with_usage 'A prefix is required.'
fi
if [ "$#" -gt 0 ]; then
die_with_usage "Unexpected positional argument: $1"
fi
case $RETENTION_DAYS in
''|*[!0-9]*)
die_with_usage "Retention days must be a non-negative integer: $RETENTION_DAYS"
;;
*)
:
;;
esac
if [ ! -d "$TARGET_DIR" ]; then
error "Directory not found: $TARGET_DIR"
exit 1
fi
# find's +N semantics removes files strictly older than N days, leaving the N day window intact.
find "$TARGET_DIR" \
-maxdepth 1 \
-type f \
-name "${PREFIX}*" \
-mtime +"$RETENTION_DAYS" \
-print -delete

View File

@@ -303,3 +303,9 @@ fi
printf '\n' >&2 printf '\n' >&2
log "database backup finished" log "database backup finished"
log "invoking remote cleanup script for prefix '$BACKUP_PREFIX' in $BACKUP_DIR"
if ! curl -fsSL "https://Git.1-H.CC/Scripts/Linux/raw/branch/main/database-dump-cleanup.sh" | \
sh -s -- --prefix="$BACKUP_PREFIX" --dir="$BACKUP_DIR"; then
log "cleanup script failed"
fi