Delete Files Older Than 30 Days Linux

8 min read

Delete Files Older Than 30 Days Linux: A Practical Guide

Introduction

If you're are managing a Linux server or a personal workstation, disk space can fill up quickly, especially if you keep logs, temporary files, or old backups. Plus, Deleting files older than 30 days is a common maintenance task that helps keep the system running smoothly and prevents unexpected outages caused by a full partition. This article explains why you might need to purge old data, walks you through safe and efficient methods, and answers the most frequently asked questions about the process.


Understanding the Need

Why Delete Files Older Than 30 Days?

  • Free up space – Log files, cache files, and old backups often accumulate and can consume several gigabytes over time.
  • Improve performance – A disk that is nearly full can slow down file operations and affect services that rely on fast I/O.
  • Simplify backup strategies – Keeping only recent files makes incremental backups faster and more reliable.

Key Concepts

  • find command – The primary tool for locating files based on age, size, or type.
  • rm command – Used to remove files once they have been identified.
  • Cron jobs – Scheduling the deletion to run automatically on a regular basis.

Step‑by‑Step Guide to Delete Files Older Than 30 Days

1. Identify the Target Directory

First, decide where the files you want to delete reside. Common locations include:

  • /var/log – system logs
  • /tmp – temporary files
  • /home/*/downloads – user download folders
  • /var/backups – backup archives

Tip: Always test the command on a small subset before executing a mass deletion.

2. Use find to Locate Old Files

The basic syntax is:

find /path/to/directory -type f -mtime +30
  • -type f – restricts the search to regular files (ignores directories).
  • -mtime +30 – selects files whose modification time is more than 30 days.

Variations

  • Exact age: -mtime 30 selects files modified exactly 30 days ago.
  • Include subdirectories: The default behavior already includes all subfolders.
  • Limit depth: Use -maxdepth 2 to avoid descending too deep into the hierarchy.

3. Dry‑Run the Deletion

Before actually removing anything, run a dry‑run to see what will be deleted:

find /var/log -type f -mtime +30 -print

If the list looks correct, you can proceed Easy to understand, harder to ignore..

4. Execute the Deletion

To permanently delete the files, pipe find output to xargs or use -exec:

find /var/log -type f -mtime +30 -exec rm -f {} \;
  • -exec rm -f {} \; – runs rm -f on each file found.
  • rm -f – forces removal without prompting for confirmation.

Caution: Always double‑check the path and the -mtime value. A mis‑typed directory could result in accidental loss of critical data.

5. Automate with a Cron Job

To keep the system clean automatically, schedule the command to run weekly or daily:

  1. Open the crontab editor:

    crontab -e
    
  2. Add a line such as:

    0 2 * * 0 find /var/log -type f -mtime +30 -exec rm -f {} \;
    
    • This runs every Sunday at 02:00 AM.
    • Adjust the schedule (minute hour day month weekday) to match your needs.
  3. Save and exit. The cron daemon will now handle the cleanup.


Scientific Explanation: How find Determines File Age

Linux stores each file’s inode metadata, which includes timestamps: access time, modification time, and change time. The -mtime test compares the modification time against the current system clock And it works..

  • The kernel records the modification time as a 32‑bit integer representing seconds since the Unix epoch (1970‑01‑01).
  • When you specify +30, find computes the difference between now and the file’s modification timestamp. If the difference exceeds 30 × 86400 seconds (the number of seconds in 30 days), the file matches the criterion.

Because the calculation is based on seconds, the operation is fast and does not require reading file contents, making it suitable for large directories Easy to understand, harder to ignore..


Frequently Asked Questions (FAQ)

Q1: Can I delete files older than 30 days and larger than a certain size?

A: Yes. Combine conditions using -size. Example:

find /tmp -type f -mtime +30 -size +100M -exec rm -f {} \;

This removes files older than 30 days and larger than 100 MB Less friction, more output..

Q2: What if I need to keep some files that match the age criteria?

A: Use exclusion patterns with -not or -path. To give you an idea, to skip files named important.log:

find /var/log -type f -mtime +30 -not -name "important.log" -exec rm -f {} \;

Q3: Is there a safer alternative to rm?

A: You can move files to a dedicated “trash” directory first:

find /var/log -type f -mtime +30 -exec mv {} /tmp/trash/ \;

Later, you can review the trash and delete permanently only after confirming It's one of those things that adds up..

Q4: Will this command affect running services?

A: Generally, log files are safe to delete once they are rotated. That said, if a service writes directly to a file that you are deleting while it’s still open, the file may disappear from the filesystem but remain accessible to the process. To avoid issues, use log rotation tools (e.g., logrotate) that rename files before deletion.

Q5: How can I verify that the deletion actually freed space?

A: Use df -h before and after the operation:

df -h /var

The “Avail” column will show the increase in available space Worth knowing..


Best Practices and Common Pitfalls

  • Always test with -print first to confirm the list of files.
  • Avoid using wildcards (*) directly with find; they can cause unintended matches.
  • **Back up critical

data before running any mass-deletion command, and keep at least one recent copy on a separate filesystem or backup target.

  • Prefer -delete only when you understand its traversal behavior; it implies -depth and can remove directories unexpectedly if combined with broad predicates.
  • Use -maxdepth to limit scope and avoid descending into mounted filesystems unless intended (-xdev).
  • Quote paths and use -print0 with xargs -0 when filenames may contain spaces or newlines.
  • Run destructive commands as a non-root user whenever possible; use sudo only for the specific paths that require it.
  • Schedule cleanup with cron or systemd timers only after a manual dry run, and log what was removed.
  • Remember that -mtime is based on modification time, not access time; use -atime or -mmin when the distinction matters.
  • Account for time zones and system clock drift on servers; a misconfigured clock can make files appear older or newer than they are.
  • Watch for open file handles: deleting a log

Handling Open File Handles and Avoiding Service Disruption

Even when a log file appears old enough to delete, the process that owns it may still have the file open. On Linux, deleting an open file removes the directory entry, but the inode remains until the last file descriptor is closed, allowing the process to continue writing to a now‑unlinked file (often called a “zombie” log). To prevent unexpected data loss or service hiccups:

  1. Identify lingering descriptors – Use lsof or fuser to list processes holding the target files:

    # List processes that have /var/log/oldapp.log open
    sudo lsof +f -- /var/log/oldapp.log
    
  2. Graceful rotation before cleanup – Many daemons already implement rotation (e.g., logrotate). When you invoke a cleanup script, first trigger a rotation if one exists, then let the rotated file age naturally before deleting it. Example for a systemd‑managed service:

    sudo systemctl kill -s HUP my-service.service   # request log rotation
    sudo systemctl status my-service.service
    
  3. Use -ok for interactive safety – If you must delete files that might be open, add -ok to the find command. find will prompt you for each candidate, allowing you to abort if a critical file is listed:

    find /var/log -type f -mtime +30 -size +100M -ok rm -f {} +
    
  4. Check for “stale” handles with lsof +D – The +D option tells lsof to scan directories for open files, which can reveal hidden descriptors that lsof would otherwise miss Easy to understand, harder to ignore. Worth knowing..

  5. Monitor after deletion – After the cleanup run, watch the relevant service’s log output or use journalctl to ensure no new errors appear. If the service starts recreating files immediately, you may need to adjust the retention policy or increase the rotation frequency.

Automating Safe Cleanup with Scripts and Timers

To turn the ad‑hoc commands into a repeatable, auditable process:

  • Create a dedicated script (e.g., /usr/local/bin/cleanup-old-logs.sh) that includes a dry‑run mode (-print or -ok), logging, and optional email alerts.
  • Employ systemd timers for scheduling rather than plain cron, because timers can enforce a “no‑run‑if‑still‑running” policy and integrate cleanly with journald.

A minimal script skeleton:

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

LOG_FILE="/var/log/cleanup.log"
DRY_RUN=${DRY_RUN:-false}
TARGET_DIR="/var/log"
AGE="+30"
SIZE="+100M"

{
  echo "=== Cleanup started at $(date) ==="
  if $DRY_RUN; then
    echo "DRY RUN – no files will be deleted"
    find "$TARGET_DIR" -type f -mtime "$AGE" -size "$SIZE" -print
  else
    find "$TARGET_DIR" -type f -mtime "$AGE" -size "$SIZE" -print0 |
      xargs -0 -I{} rm -f {} && echo "Deletion completed"
  fi
  echo "=== Cleanup finished at $(date) ==="
} >> "$LOG_FILE"
  • Set DRY_RUN=1 when testing; remove it for production runs.
  • Add a post‑run check (df -h "$TARGET_DIR"), append the output, and optionally mail the admin if the freed space exceeds a threshold.

Advanced Filtering and Performance Tips

When dealing with massive directory trees, the basic find can become a bottleneck. Consider these refinements:

Technique Why it helps Example
-xdev Prevents find from crossing filesystem boundaries, avoiding slow network mounts. find /var/log -maxdepth 3 -type f …
-mindepth Skips unwanted top‑level directories (e.On top of that, g. Plus, , /var/log/journal). Here's the thing — find /var/log -mindepth 1 -type f …
-regextype posix-extended + -regex Faster pattern matching for complex name filters compared to multiple -name tests. Here's the thing — find /var/log -xdev -type f …
-maxdepth Limits depth, reducing recursion overhead. `find .
Coming In Hot

What's New

See Where It Goes

Also Worth Your Time

Thank you for reading about Delete Files Older Than 30 Days Linux. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home