A Safe Old-File Cleanup Script With find That Won’t Delete the Wrong Thing

The scariest line in operations is a find ... -delete run against the wrong directory. It does not warn you, it does not ask, and it is fast.

Nearly every server accumulates old files that need clearing on a schedule: log archives, export dumps, cache directories, temporary uploads. The job is usually one line of find. That is exactly why it is dangerous. A stray space, a variable that expanded to empty, a working directory that was not what you assumed, and the same command that tidied a cache directory yesterday empties something load-bearing today. This piece builds a cleanup you can schedule without that fear. It uses GNU find (findutils), xargs and bash 5.2, and it is deliberately boring.

If the reason you are cleaning up is that a disk is filling, deleting old files is only half the answer; how the box behaves when it runs out of headroom is the other half, which I cover in swap on a modern Linux server.

Free · 4 minutes

Is your engineering team shipping safely, or quietly accumulating risk?

Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.

Anchor to an absolute path, and filter tightly

The first rule: never let find start from an implicit or relative path. Name the directory absolutely, every time, so the command behaves identically whether it is run by hand, from cron, or from a systemd timer. The second rule: filter down to exactly what you mean to remove before you go anywhere near a delete.

Three predicates carry the weight. -type f restricts the match to regular files, so you never delete directories or special files by accident. -xdev keeps the traversal on a single filesystem, so a mounted volume underneath your target is left alone. And -mtime +N selects by age. That last one has a rounding rule worth knowing precisely: find measures age in whole 24-hour periods and discards the fractional part, so -mtime +30 matches files whose data was last modified at least 31 days ago, not 30. If you need a cutoff anchored to the start of the day rather than the exact time of the run, add -daystart; if you need an absolute date, -newermt '2026-01-01' is clearer than arithmetic on -mtime.

Always preview before you delete

The single habit that prevents most disasters is running the exact same filter with -print before you attach any deletion. Read the list. If it contains something you did not expect, you have just caught the mistake for free.

# 1. Preview first. Same filter, no deletion.
find /var/log/myapp/archive -xdev -type f -mtime +30 -print

# 2. Same filter, NUL-separated, handed to rm safely.
find /var/log/myapp/archive -xdev -type f -mtime +30 -print0 \
  | xargs -0 --no-run-if-empty rm -f --

Why -print0 and xargs -0 rather than a plain pipe? Because filenames can contain spaces, tabs and even newlines, and the default whitespace splitting will happily tear one such name into several bogus arguments. -print0 separates paths with a NUL byte, which cannot appear in a filename, and xargs -0 reads them back the same way. --no-run-if-empty stops xargs invoking rm at all when nothing matched, and the trailing -- tells rm that anything after it is a filename, so a file called -rf cannot be read as a flag.

-delete versus -exec rm

find has a built-in -delete action. It forks no processes, it handles awkward filenames natively, and it is the neatest option once you trust the filter. But it has a footgun. -delete implies -depth, which reorders the traversal to process a directory’s contents before the directory itself, and because -delete is an action rather than a test, its position in the expression matters. Write find . -delete -name '*.tmp' expecting it to remove only temp files and it will instead delete everything, because -delete fires before -name is ever evaluated. The tests must come first.

-exec rm {} + batches matches into as few rm calls as possible and is efficient; -exec rm {} \; forks one rm per file and is slower. I reach for -print0 | xargs -0 in scheduled jobs for one reason: it decouples finding from deleting, so I can drop a tee in the middle and record exactly what was removed. That audit trail is worth more than the microseconds it costs.

The guard that stops it hitting /

Now the full job. It refuses to run unless the target is an absolute path, is at least two segments deep, and actually exists, so an empty variable or a bare / or /var stops the script dead rather than emptying the machine. It defaults to a dry run and only deletes when you pass --apply. It logs every removed path. And it uses a mktemp manifest cleaned up by a trap, a pattern I go into in Bash traps and mktemp.

#!/usr/bin/env bash
# safe-cleanup.sh - delete files older than N days under a fixed root.
# Dry run by default; pass --apply to actually delete.
set -euo pipefail

# --- Configuration (edit, or override via the environment) -----------------
TARGET="${CLEANUP_TARGET:-/var/log/myapp/archive}"   # absolute path only
AGE_DAYS="${CLEANUP_AGE_DAYS:-30}"                    # feeds -mtime +N
LOG="${CLEANUP_LOG:-/var/log/safe-cleanup.log}"

APPLY=0
[[ "${1:-}" == "--apply" ]] && APPLY=1

# --- Guards: refuse to run against anything dangerous ----------------------
root="$(realpath -m -- "$TARGET")"          # canonicalise, no existence needed

if [[ "$root" != /* ]]; then
  echo "Refusing: target is not an absolute path: $root" >&2; exit 1
fi
if [[ "$root" == "/" || "${root#/*/}" == "$root" ]]; then
  # Rejects "/" and single-segment roots such as "/var" or "/home".
  echo "Refusing: target is too close to the root: $root" >&2; exit 1
fi
if [[ ! -d "$root" ]]; then
  echo "Refusing: target directory does not exist: $root" >&2; exit 1
fi

# --- One filter, reused for the preview and the delete ---------------------
# -xdev: stay on one filesystem. -type f: regular files only.
# ! -path .../keep/*: never touch anything under a keep/ subdirectory.
filter=( "$root" -xdev -type f -mtime "+$AGE_DAYS" ! -path "$root/keep/*" )

if (( APPLY == 0 )); then
  echo "DRY RUN - files older than $AGE_DAYS days under $root:"
  find "${filter[@]}" -printf '%TY-%Tm-%Td  %p\n'
  echo "Nothing deleted. Re-run with --apply to remove them."
  exit 0
fi

# --- Apply: NUL-safe delete, with a manifest of what went ------------------
manifest="$(mktemp)"
trap 'rm -f "$manifest"' EXIT
ts="$(date --iso-8601=seconds)"

find "${filter[@]}" -print0 \
  | tee "$manifest" \
  | xargs -0 --no-run-if-empty rm -f --

removed="$(tr -cd '\0' < "$manifest" | wc -c)"
tr '\0' '\n' < "$manifest" | sed "s|^|$ts deleted |" >> "$LOG"
echo "Removed $removed file(s); list appended to $LOG."

The guard on line matching ${root#/*/} is the quiet hero. It strips the shortest /something/ prefix; if the result is unchanged, the path had fewer than two segments, and the script bails. That one test is what stands between a typo and an outage.

Scheduling it without surprises

Run it by hand once, read the dry-run output, then schedule it. The one caveat: a script that works in your shell can still fail under cron, because cron runs with a minimal environment and a different working directory. This script is written to survive that: absolute paths throughout, no reliance on $PATH niceties, no assumption about where it starts. If yours behaves differently on a timer, the causes are catalogued in why a bash script works by hand but fails in cron.

None of this is clever. That is the point. A cleanup job earns its keep by being the least surprising thing on the box: it deletes only what you named, only when it is old enough, only after it has shown you the list, and never, under any circumstances, the root of your filesystem.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.