ThisCalculator

Everyday

Delete Old Files in a Folder Automatically in Linux

Updated · Standard formula, shown below

Delete Old Files in a Folder Automatically in Linux

To delete old files in a folder automatically in Linux, you use a scheduled command that finds files by age and removes them, typically find with -mtime plus -delete, run by cron or a systemd timer. This article explains the exact commands, how to schedule them, and how to avoid common pitfalls.

Why Automate File Deletion?

Log files, temporary downloads, cache files, and backup archives accumulate quickly and fill up disk space. Manually deleting them is tedious and easy to forget. Automating the cleanup ensures that old files are removed on a regular schedule, keeping storage usable and preventing issues like full partitions that can crash services or stop the system from writing new data.

The Core Command: find with -mtime and -delete

The standard tool is find, which can locate files based on their modification time and then delete them in one go. The basic syntax is:

find /path/to/folder -type f -mtime +30 -delete

This deletes all regular files in /path/to/folder whose modification time is more than 30 days old. The +30 means “older than 30 days� (strictly greater than 30*24 hours). If you use 30 without the plus, it matches files modified exactly 30 days ago. Use -mmin for minutes instead of days, e.g., -mmin +1440 for 24 hours.

Scheduling with cron

To run the deletion automatically, add a cron job. Edit your user’s crontab with crontab -e and add a line like:

0 3 * * * find /path/to/folder -type f -mtime +30 -delete

This runs every day at 3:00 AM. The five fields are minute, hour, day of month, month, and day of week. You can also place a script in /etc/cron.daily to run once per day at the system’s configured time.

Using systemd Timers (Modern Alternative)

Many modern distributions prefer systemd timers over cron. Create a service file and a timer file in /etc/systemd/system/:

# /etc/systemd/system/cleanup.service
[Unit]
Description=Delete old files in /tmp

[Service]
Type=oneshot
ExecStart=/usr/bin/find /tmp -type f -mtime +7 -delete
# /etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Then enable and start the timer with systemctl enable --now cleanup.timer. Timers offer more flexibility (e.g., run after boot, random delay) and better logging.

Safety: Test Before You Delete

Always test the find command without -delete first to see which files would be removed:

find /path/to/folder -type f -mtime +30 -print

Review the list. To be extra safe, use -exec rm -- {} instead of -delete; it’s slightly slower but allows you to see the command in logs. Also consider using -name '*.log' to limit deletion to certain file types, and -maxdepth 1 to avoid recursing into subdirectories if you don’t want that.

Common Mistakes and Pitfalls

  • Deleting symlinks: -type f does not match symbolic links, so they remain. Use -type l to delete them separately if needed.
  • Permissions: The command must have read and write access to the folder. Running as root may be necessary for system directories.
  • Time zone: find uses the system’s local time for -mtime. If your server is in UTC and you expect local time, adjust accordingly.
  • Deleting files in use: On Linux, deleting an open file is safe (the process keeps the inode), but it may cause confusion if the process later tries to access the file by name.
  • Accidental deletion of recent files: Double-check the + sign. -mtime +30 is safe; -mtime 30 is exact, and -mtime -30 would delete files newer than 30 days, which is the opposite of what you want.

Alternatives and Advanced Options

If you need more complex logic (e.g., delete files older than X days but keep the newest N), consider using tmpwatch (or tmpreaper on Debian/Ubuntu), which is designed for temporary file cleanup. For directories that should be emptied entirely, find /path -mindepth 1 -delete removes all contents. To delete files older than a certain date, use -newermt to specify a reference date instead of relative time.

Frequently Asked Questions

How do I delete files older than 7 days but keep subdirectories?

Use find /path -type f -mtime +7 -delete. This removes only files, not directories, so the folder structure remains intact.

What if I want to delete files in subfolders too?

By default, find recurses into subdirectories, so the command already deletes old files in all subfolders. If you want to limit to the top level only, add -maxdepth 1.

Can I delete files based on access time instead of modification time?

Yes, replace -mtime with -atime for last access time, or -ctime for inode change time. Be aware that access time updates can be disabled on some filesystems (e.g., with noatime).

Is it safe to delete files in /tmp automatically?

Generally yes, but some programs store important data in /tmp. Use a conservative age (e.g., 7 days) and test first. Also, consider using systemd-tmpfiles which is the built-in mechanism for /tmp cleanup.

How do I make the deletion permanent across reboots?

Cron jobs and systemd timers are persistent by default. For cron, ensure the crontab is saved. For systemd, enable the timer with systemctl enable.

What if I accidentally delete important files?

There is no built-in undo. Check your backup or use a versioning filesystem like btrfs or ZFS. To reduce risk, move files to a trash folder instead of deleting, using mv in a script.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.