Files
Linux/database-dump-cleanup.sh

116 lines
2.1 KiB
Bash
Executable File

#!/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