Add scripts/cleanup_old_files.sh
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Delete files older than a defined number of days.
|
||||
#
|
||||
# This is a simple and practical maintenance script for temporary folders,
|
||||
# export directories, application cache folders, and backup staging areas.
|
||||
#
|
||||
# Usage:
|
||||
# bash cleanup_old_files.sh --path /var/tmp/app --days 30 --dry-run
|
||||
# bash cleanup_old_files.sh --path /var/tmp/app --days 30 --delete
|
||||
#
|
||||
# Options:
|
||||
# --path DIR Directory to scan.
|
||||
# --days N Delete files older than N days.
|
||||
# --delete Actually delete files.
|
||||
# --dry-run Show what would be deleted. This is the default behavior.
|
||||
# --help Show this help message.
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
target_path=""
|
||||
days=""
|
||||
delete_files=false
|
||||
|
||||
usage() {
|
||||
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
|
||||
}
|
||||
|
||||
log() {
|
||||
printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
|
||||
}
|
||||
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--path)
|
||||
target_path="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--days)
|
||||
days="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--delete)
|
||||
delete_files=true
|
||||
shift
|
||||
;;
|
||||
--dry-run)
|
||||
delete_files=false
|
||||
shift
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
printf 'ERROR: unknown option: %s\n' "$1" >&2
|
||||
usage >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -d "$target_path" ]] || { printf 'ERROR: directory not found: %s\n' "$target_path" >&2; exit 1; }
|
||||
[[ "$days" =~ ^[0-9]+$ ]] || { printf 'ERROR: --days must be a positive number.\n' >&2; exit 1; }
|
||||
|
||||
log "Scanning '${target_path}' for files older than ${days} days."
|
||||
|
||||
if [[ "$delete_files" == true ]]; then
|
||||
log "Delete mode enabled."
|
||||
find "$target_path" -type f -mtime "+${days}" -print -delete
|
||||
log "Cleanup finished."
|
||||
else
|
||||
log "Dry-run mode enabled. No files will be deleted."
|
||||
find "$target_path" -type f -mtime "+${days}" -print
|
||||
log "Dry-run finished."
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user