Skip to content
GreenSnippets

Delete files older than N days

Safely remove old log or temp files with find, previewing first and handling unusual filenames.

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

dir="${1:?usage: $0 DIRECTORY [DAYS]}"
days="${2:-7}"

[[ -d "$dir" ]] || { echo "Not a directory: $dir" >&2; exit 1; }

# Preview
find "$dir" -type f -mtime "+$days" -print

read -r -p "Delete these files? [y/N] " answer
if [[ "$answer" == "y" ]]; then
  find "$dir" -type f -mtime "+$days" -delete
fi

Example / expected output

Output
$ ./clean.sh /var/log/myapp 14

How it works

Run the command without -delete first to see what would be removed. -mtime +7 means modified more than 7 days ago. -type f avoids touching directories, and -print0 with xargs -0 (or the built-in -delete) copes with spaces and newlines in names. Always point find at a specific directory, never at a variable that might be empty.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.