Skip to content

Delete Old Log Files

cleanupfindcron-ready
6 min read
Matching toolCron Job Builder

Quick Answer

The find command with -mtime locates files by age. Running find /var/log -name "*.log" -mtime +30 -delete removes every .log file in /var/log that has not been modified in more than 30 days. Without periodic cleanup, log files accumulate silently until a disk fills and your web server can no longer write access logs, your database stops accepting writes, or your application crashes mid-transaction. On a busy server generating 50 MB of logs per day, a 30-day window means 1.5 GB consumed before any file gets touched. Before running the delete, swap -delete for -print to preview exactly what will be removed — an essential safety step when running on production directories. find ships with findutils on every Linux distribution — no extra packages required. Schedule with cron: 0 3 * * 0 find /var/log -name "*.log" -mtime +30 -delete to run weekly at 3am.

This is one of the 25

Log cleanup is the second script in the sysadmin set, right after the disk-space check that tells you it is needed. The guide puts the two on one cron schedule and adds the retention, backup and SSL checks that share the same failure: nothing pruned, nothing noticed. Full guide: 25 Bash Scripts Every Linux Sysadmin Needs.

My SSD hit zero free bytes on a Tuesday, and three unrelated things broke within about a minute of each other — a build, a database write, and my editor's autosave all failing at once. A full disk doesn't announce itself politely; every program that needs to write a single byte starts throwing errors, so the symptoms scatter and the cause hides. It took me an embarrassing while to run df, see / at 100%, and longer still to trace it back to one app I'd left running for a week that had been quietly appending to a log file the whole time.

Nothing was wrong with the app. It was doing what loggers do. The problem was that nothing was ever pruning what it wrote, so a directory I never looked at grew until it swallowed the last gigabyte on the drive. That's the trap with logs: they're individually tiny and collectively fatal, and they fail you silently right up until everything that touches the disk gives out at the same moment. The script below is what I now point at any directory that grows without bound, so old log files age out on a schedule instead of waiting to take the whole machine down — the part I wasn't going to sit through twice.

The cleanup script that saved my SSD

Paste this into a file called cleanlog.sh. Change LOG_DIR and DAYS to match your setup. Run with -print first before using -delete.

bash
#!/bin/bash # Delete Old Log Files # find /var/log -name "*.log" -mtime +30 -delete removes every log file older than 30 days in one command. # Always run with -print instead of -delete first — it previews exactly which files will be removed # without touching anything. Swap to -delete when you're satisfied with the list. # SAFE: swap -delete for -print to preview first. # # USAGE: ./cleanlog.sh # REQUIRES: bash, find (pre-installed on all Linux/macOS) set -euo pipefail LOG_DIR="/var/log/myapp" # ← your log folder DAYS=30 # ← delete logs older than this many days echo "Cleaning logs older than $DAYS days in $LOG_DIR..." find "$LOG_DIR" -type f -name "*.log" \ -mtime +$DAYS -delete echo "✓ Done. Cleaned logs older than $DAYS days."

What this does, line by line

find "$LOG_DIR" searches your log folder. -type f limits results to files only (skips subdirectories). -name "*.log" matches only log files. -mtime +$DAYS filters to files last modified more than DAYS days ago. -delete removes them. Replace -delete with -print anytime to preview without deleting.

Setting it up without nuking the wrong files

Step 1 — Create the file

bash
nano cleanlog.sh

Paste the script, then Ctrl+X → Y → Enter to save.

Step 2 — Set your paths and age limit

VariableExampleWhat it means
LOG_DIR/var/log/nginxThe folder containing your log files
LOG_DIR/home/user/app/logsA custom app log folder
DAYS7Delete logs older than 1 week
DAYS30Delete logs older than 1 month (default)
DAYS90Delete logs older than 3 months

Step 3 — ALWAYS preview before deleting

Before you run the script for the first time, swap -delete for -print to see exactly which files would be removed:

bash
# Preview mode — shows files that WOULD be deleted, removes nothing find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS -print

Review the output. If it looks right, switch back to -delete and run for real.

Step 4 — Make it executable and run it

bash
chmod +x cleanlog.sh ./cleanlog.sh

Schedule with Cron

Running this once manually is useful. Running it automatically every week is the goal.

bash
crontab -e
bash
# Run every Sunday at 3am 0 3 * * 0 /home/user/cleanlog.sh # Run every day at midnight 0 0 * * * /home/user/cleanlog.sh # Run on the 1st of every month 0 0 1 * * /home/user/cleanlog.sh

Log output to a file

Add >> /var/log/cleanlog.log 2>&1 to the end of your cron line so you have a record of every cleanup run and any errors.

Versions for messier log directories

If the directory holds dated folders rather than loose files, and you want to keep the newest N no matter how old they are, use Log Retention Cleanup instead: it dry-runs by default and refuses a bad --keep or --days value before it deletes anything.

Clean multiple file types at once

bash
#!/bin/bash LOG_DIR="/var/log/myapp" DAYS=30 # Delete .log AND .gz (compressed log) files older than DAYS find "$LOG_DIR" -type f \( -name "*.log" -o -name "*.gz" \) \ -mtime +$DAYS -delete echo "✓ Cleaned .log and .gz files older than $DAYS days"

Delete logs and report how much space was freed

bash
#!/bin/bash LOG_DIR="/var/log/myapp" DAYS=30 # Measure disk usage before BEFORE=$(du -sh "$LOG_DIR" | awk '{print $1}') find "$LOG_DIR" -type f -name "*.log" -mtime +$DAYS -delete # Measure disk usage after AFTER=$(du -sh "$LOG_DIR" | awk '{print $1}') echo "✓ Done. Before: $BEFORE → After: $AFTER"

Clean logs across multiple directories

bash
#!/bin/bash DAYS=30 DIRS=("/var/log/nginx" "/var/log/myapp" "/home/user/app/logs") for dir in "${DIRS[@]}"; do [ -d "$dir" ] || continue # skip if folder doesn't exist echo "Cleaning $dir..." find "$dir" -type f -name "*.log" -mtime +$DAYS -delete done echo "✓ All directories cleaned."

How this deletes the wrong thing

Not previewing with -print first

The most common mistake. Always run with -print before -delete the first time on any new directory. One wrong path and you could delete the wrong files permanently.

Deleting system logs you shouldn't touch

Avoid pointing LOG_DIR at /var/log directly — that includes system logs that your OS needs. Always target a specific subfolder like /var/log/nginx or /var/log/myapp. Database transaction logs require a different approach — use the MySQL database backup script instead of deleting them with find.

-mtime counts in full 24-hour periods

-mtime +30 means strictly more than 30 full days ago, not "30 days ago today." A file from exactly 30 days ago won't match — it needs to be 31+ days old. Use -mtime +29 if you want to catch files from day 30.

Understanding the Commands

Command / FlagWhat it does
find $LOG_DIRSearches recursively through the specified directory
-type fMatches files only — ignores directories and symlinks
-name "*.log"Matches files ending in .log — change to *.gz, *.tmp, etc.
-mtime +30Matches files modified more than 30 full days ago
-printPrints matching files to the terminal — safe preview mode
-deleteDeletes matching files permanently — always preview first

Frequently Asked Questions

How do I automatically delete old log files in Linux?

Use the find command: find /var/log/myapp -name '*.log' -mtime +30 -delete. This removes all .log files older than 30 days. Add it to cron with crontab -e to run it automatically on a schedule.

How do I safely preview what find -delete will remove?

Swap -delete for -print in your command. It prints the matching files to your terminal without touching them. Review the list, and when you're confident, switch back to -delete.

What does -mtime +30 mean in the find command?

-mtime +30 matches files whose last modification time was more than 30 full 24-hour periods ago. Use +7 for a week, +90 for three months. The + means strictly greater than.

How do I delete files older than 30 days in Linux?

Run: find /path/to/folder -type f -mtime +30 -delete. This finds all files modified more than 30 days ago and deletes them. Always test with -print before using -delete. For files that accumulate without an age-based pattern, the find duplicate files script identifies redundant copies by content hash.

Part of the bash snippets collection

Raw script, MIT licensed: scripts/delete-old-log-files.sh on GitHub

PAID RESOURCE — $9

The Production Bash Toolkit

An operational script system + a 30-function shared library + a 52-page field guide. The production layer the free snippets don't cover.

Get the Toolkit →
curl -O bashlib-starter.sh

Get the bashlib starter

Ten functions I source into every script on my own boxes — strict-mode setup, an ERR trap that names the failing line, lock and timeout wrappers, and cleanup that runs on every exit path. After that, a short email only when something breaks on a real box and I've worked out why, about twice a month. One-click unsubscribe.

BashSnippets logo

Written by Travis

Creator of BashSnippets.xyz

bashsnippets.xyz/about

Related Snippets

Frequently Asked Questions

faq — snippet

How do I run this script?

Save the script, set LOG_DIR and DAYS, preview with -print instead of -delete first, then chmod +x and run.

faq — snippet

Does this work on macOS?

Yes. find -mtime works on macOS. Use -print before -delete to preview matches on BSD find.

faq — snippet

How do I safely preview what find -delete will remove?

Replace -delete with -print in your find command. Review the output, then swap back to -delete when satisfied.

faq — snippet

What does -mtime +30 mean in the find command?

Files last modified more than 30 days ago. +30 means strictly older than 30 days; -mtime 30 means exactly 30 days.