Bash Script to Clean Up Old Files and Alert on High Disk Usage
bashDeletes files older than a specified number of days, logs actions, and alerts if disk usage exceeds a defined threshold. Designed for Linux servers, NAS systems, and Proxmox homelabs. Read more here.
bashlinuxhomelabdisk managementautomationcleanupmonitoring
Script Code
Bashbash
#!/usr/bin/env bash
set -euo pipefail
# === CONFIG DEFAULTS ===
TARGET_DIR="${1:-/var/log}"
DAYS_OLD="${2:-14}"
LOG_FILE="${3:-/var/log/homelab_cleanup.log}"
DISK_PATH="${4:-/}"
DISK_THRESHOLD="${5:-85}"
DRY_RUN="${DRY_RUN:-false}"
timestamp() { date +"%Y-%m-%d %H:%M:%S"; }
log() {
echo "$(timestamp) $*" | tee -a "$LOG_FILE" >/dev/null
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || { echo "Missing required command: $1" >&2; exit 1; }
}
main() {
require_cmd find
require_cmd df
require_cmd awk
if [[ ! -d "$TARGET_DIR" ]]; then
echo "Target directory does not exist: $TARGET_DIR" >&2
exit 1
fi
log "=== Cleanup start ==="
log "TARGET_DIR=$TARGET_DIR DAYS_OLD=$DAYS_OLD DISK_PATH=$DISK_PATH THRESHOLD=${DISK_THRESHOLD}% DRY_RUN=$DRY_RUN"
CANDIDATES_COUNT="$(find "$TARGET_DIR" -type f -mtime "+$DAYS_OLD" 2>/dev/null | wc -l | tr -d ' ')"
log "Found $CANDIDATES_COUNT files older than $DAYS_OLD days."
if [[ "$CANDIDATES_COUNT" -gt 0 ]]; then
if [[ "$DRY_RUN" == "true" ]]; then
log "DRY RUN: Listing files that would be deleted:"
find "$TARGET_DIR" -type f -mtime "+$DAYS_OLD" -print | tee -a "$LOG_FILE" >/dev/null
else
log "Deleting files..."
find "$TARGET_DIR" -type f -mtime "+$DAYS_OLD" -print -delete | tee -a "$LOG_FILE" >/dev/null
log "Deletion complete."
fi
fi
USED_PCT="$(df -P "$DISK_PATH" | awk 'NR==2 {gsub(/%/,"",$5); print $5}')"
log "Disk usage for $DISK_PATH is ${USED_PCT}%."
if [[ "$USED_PCT" -ge "$DISK_THRESHOLD" ]]; then
log "ALERT: Disk usage is high (${USED_PCT}% >= ${DISK_THRESHOLD}%)."
echo "ALERT: Disk usage high on $DISK_PATH: ${USED_PCT}%"
fi
log "=== Cleanup end ==="
}
main "$@"Get new scripts weekly.
Subscribe to receive fresh PowerShell scripts, automation tips, and IT workflow improvements.
Subscribe to Newsletter