Delete files older than N days
Safely remove old log or temp files with find, previewing first and handling unusual filenames.
- Bash
- GreenSnippets
- MIT
#!/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
fiExample / expected output
$ ./clean.sh /var/log/myapp 14How 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.
Related snippets
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- Python Tested
Read a CSV file as dictionaries
Stream CSV rows as dicts keyed by header with csv.DictReader, handling UTF-8 BOMs and quoted commas.
- Python Tested
Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.

