How to Delete Files and Folders Older Than X Days in Linux

Illustrated infographic summarizing: Delete Files and Folders Older Than X days

By Greg Nowak. Updated 4 November 2026.

Old exports, generated reports, and temporary files can quietly fill a Linux server. A cleanup command can reclaim space, but it needs to reflect how your team uses those files. Something nobody has modified for six months may still be a customer’s only copy.

The practical approach is to agree what can go, preview the selection, delete eligible files, and handle empty folders separately. The examples below use GNU find, common on Linux, and retain the original 180-day example. Replace /srv/myapp/exports with the specific directory you intend to clean.

The short answer: delete files older than X days in Linux

Preview first, then run the same command with -delete. This removes regular files in /srv/myapp/exports last modified more than 30 days ago:

find /srv/myapp/exports -type f -mtime +30 -print     # preview
find /srv/myapp/exports -type f -mtime +30 -delete    # delete

Change the number for another age, add -name '*.log' to limit it to one kind of file, and keep the path specific: never point it at / or a home folder. Because find counts whole days, -mtime +30 starts at 31 days old. The sections below cover the choices behind a cleanup that is safe to schedule.

Decide what your retention rule covers

Before running anything, ask the application owner what the directory contains and how files get there. For an agency, that may mean checking with both the developer and the person responsible for the client account. For an internal operations team, it means identifying who can authorize removal and answer a later recovery request.

Choose the cleanup method according to what the files mean to the business.
Content Practical approach Decision to confirm
Generated exports and reports Delete regular files by modification age. Can they be recreated from retained data?
Customer uploads and project archives Select through an agreed retention process. What must remain available, and who approves removal?
Empty application folders Review and remove them separately. Does the application expect the folder structure to exist?
Shared system temporary files Review the operating system’s existing cleanup policy. Is another service already managing these paths?

If disposable exports and permanent documents share a directory, separate them or define a reliable filter first. Age alone cannot tell you which files matter.

Understand what “older than X days” means

-mtime checks when file contents were last modified. It does not establish when a customer uploaded the file, when a project finished, or when the file was last needed. Copies and restored backups may preserve older modification timestamps.

GNU find rounds elapsed time down to whole 24-hour periods. Consequently, -mtime +180 selects files at least 181 full days old; -mtime +30 starts at 31 days. These are elapsed periods, rather than calendar dates, as explained in the GNU age-range documentation.

Write that boundary into the maintenance instructions. If retention starts from an invoice date or an account closure, use the application’s records to identify eligible files.

Preview the files before deleting them

Start with this read-only command:

find '/srv/myapp/exports' -xdev -depth -mindepth 1 -type f -mtime +180 -print

-type f selects regular files. -mindepth 1 excludes the starting directory from the tests and actions. -depth visits children before their parent directory, keeping the preview’s traversal consistent with the deletion step. See GNU’s directory traversal guidance.

-xdev prevents descent into directories on other filesystems. Using the directory path directly includes hidden entries within it, whereas a shell-expanded path such as /tmp/* normally misses hidden entries at that level. By default, GNU find does not follow symbolic links; adding -L changes that behavior. These controls are covered in the GNU Findutils manual.

Review the paths with someone who understands the application. If only CSV exports are disposable, add -name '*.csv' before -print, and use the same filter in the deletion command. Keep the pattern quoted so the shell does not expand it.

Delete the matching regular files

Once the selection is agreed and you have confirmed how any irreplaceable data can be recovered, run:

find '/srv/myapp/exports' -xdev -depth -mindepth 1 -type f -mtime +180 -delete -print

The trailing -print reports paths successfully deleted. Keep -delete after the selection tests: moving it earlier changes what gets removed. It also enables depth-first traversal, which makes -prune ineffective. GNU documents these behaviors in its deletion guidance.

Avoid selecting directories by age and passing them to rm -rf. An old directory can contain recently modified files, and recursive removal would delete those too. Selecting regular files by their own timestamps keeps the rule understandable.

Clean up empty folders separately

Preview empty directories that meet the same age rule:

find '/srv/myapp/exports' -xdev -depth -mindepth 1 -type d -empty -mtime +180 -print

If those folders are disposable, delete them with:

find '/srv/myapp/exports' -xdev -depth -mindepth 1 -type d -empty -mtime +180 -delete -print

Deleting a file changes its parent directory’s modification time, so a folder emptied by the first pass may remain. To remove empty folders regardless of age, omit -mtime +180 from both folder commands—but first confirm that the application does not need them.

The folder preview has a further limit: deletion can empty parent directories, making additional parents eligible during the same depth-first pass. The preview lists folders empty at that moment.

Turn the command into a maintainable routine

A preview is a snapshot. The deletion command searches again, and files may change between runs. Coordinate cleanup with the export-producing job, or keep completed exports separate from work in progress.

Before scheduling through cron or a systemd timer, document the path, age rule, exclusions, job account, responsible person, and recovery procedure. Use only the permissions the task needs. Capture errors, monitor the exit status, and make failures visible to someone who can act. Watch the first scheduled runs before treating cleanup as routine.

For shared /tmp directories on systems using systemd, review systemd-tmpfiles and the existing tmpfiles.d configuration first. It already supports age-based cleanup; understand that policy before adding another job.

If your team has inherited a cleanup script with unclear rules or ownership, I can help review it with your developers or hosting provider, agree the retention decisions, and document the handover. Contact Greg to discuss your server maintenance setup.

Quick answers

Delete files older than 7 days

find /path -type f -mtime +6 -delete removes files at least 7 full days old; -mtime +7 waits until they are 8 days old. Preview with -print in place of -delete.

Delete files by date rather than by age

Give GNU find a fixed date: find /path -type f ! -newermt '2026-01-01' -print lists files last modified before 1 January 2026. Swap -print for -delete once the list is right.

Older than a number of minutes or hours

-mmin +120 selects files modified more than 120 minutes ago. It suits upload and cache folders that turn over within a day.

Remove old temporary files on a schedule

Put the tested command in a cron job or systemd timer that runs as the account owning the files, not as root, and keep its output. For a temporary folder, one line in a tmpfiles.d file does the same without a script: d /srv/myapp/tmp 0750 myapp myapp 30d creates the folder and clears entries older than 30 days.

Related on GrN.dk

Need help with this kind of work?

Discuss your server maintenance setup with Greg Get in touch with Greg.

Sources

Latest articles

WordPress jobs running late? Learn how to separate scheduling problems, task errors and a growing backlog, then choose the right scheduler or runner.

Before changing an AI workflow, check that it still does the job. Use realistic examples, clear release criteria and a comparison with the version running today.

Sending an invoice does not mean it has arrived. Understand delivery statuses, the system requirements coming in 2027, and how focused AI support can help finance teams handle errors and follow-up.

Before scaling AI content, check the pages you already have. Verify claims, resolve overlapping coverage, and give WordPress reviewers control over publication.

Build a refund approval workflow in n8n and Stripe that shows reviewers the exact action, expires old approvals and tracks refunds through to completion.

A timeout can hide a successful job creation. Use stable operation IDs, destination API rules and a clear recovery process to prevent duplicate work.

Does your ChatGPT subscription cover website translation? Understand API credits, access and a WordPress workflow that turns approved Danish content into translation drafts.

An internal AI can keep quoting a deleted policy. Check document updates, indexed passages and cached answers to find where outdated guidance survives.

Codex drew all ten pages of my Ninjai comic from the script Claude wrote in the first test. What made that handover work, and what it cost.

ChatGPT delivered ten painted comic pages; Claude drew one page in code. A practical look at AI tool selection, creative briefs and approval decisions.