WEBTOOLIST.
STATIC WEB PLATFORM
NO ACCOUNTS / NOTHING TO INSTALL

$ webtoolist --script safe-log-cleanup

Safe Log Cleanup

Delete rotated log files older than a set number of days, with a dry-run first.

category System Administration shell Bash 4+ updated 2026-09-12
logscleanupdiskmaintenance
Safety notes
  • Deletes files. The script defaults to a dry run; pass --delete only after reviewing the list.
  • Only matches names ending in .log.* or .gz, never the active .log file.
commands involved: rm

Dependencies: find, date

Usage

  • Set LOG_DIR, or pass a directory as the first argument.
  • Run without flags to preview matches.
  • Add —delete to remove them; —days N changes the age threshold (default 14).

Script

#!/usr/bin/env bash
set -euo pipefail

usage() {
  echo "usage: $0 [--days N] [--delete] [LOG_DIR]" >&2
  exit 2
}

days=14
delete=0
log_dir=""

while (($#)); do
  case "$1" in
    --days)   [[ ${2:-} =~ ^[0-9]+$ ]] || usage; days="$2"; shift 2 ;;
    --delete) delete=1; shift ;;
    -h|--help) usage ;;
    -*)       usage ;;
    *)        log_dir="$1"; shift ;;
  esac
done

log_dir="${log_dir:-/var/log}"
[[ -d "$log_dir" ]] || { echo "not a directory: $log_dir" >&2; exit 1; }

mapfile -t victims < <(
  find "$log_dir" -maxdepth 1 -type f \
    \( -name '*.log.*' -o -name '*.log-*' -o -name '*.gz' \) \
    -mtime +"$days" -print | sort
)

if ((${#victims[@]} == 0)); then
  echo "no log files older than ${days} days in $log_dir"
  exit 0
fi

printf '%s\n' "${victims[@]}"

if ((delete)); then
  printf 'deleting %d file(s) older than %d days...\n' "${#victims[@]}" "$days"
  printf '%s\0' "${victims[@]}" | xargs -0 rm -f --
  echo "done"
else
  echo "(dry run) re-run with --delete to remove these files"
fi

Example

sudo ./safe-log-cleanup --days 30 /var/log
sudo ./safe-log-cleanup --days 30 --delete /var/log

Notes

  • The active application log is deliberately never matched.
  • If logrotate already handles retention, this script is redundant — check /etc/logrotate.d first.

Related scripts

Find Large Files

Locate files above a size threshold and show them largest first.

File Management

Disk Usage Report

Show filesystem usage and the largest directories under a path.

System Administration

Failed Service Report

List systemd units that are failed or restarting, with recent log lines.

System Administration