Linux: How to Delete Files Older than Number of Days

Let’s say that you have a requirement to only keep 90 days worth of files for one or more reasons:

  • Compliance for ISO 27000
  • Reduce the amount of disk space backup files are taking up

Use the Find Command with -Exec option

Requirements

  • search for files
    • -type f
  • Last Modified 90+ days ago
    • -mtime +90
  • Once it files the files, delete them, with one command
    • -exec rm {} +
    • The plus sign at the end will delete all with one line compared to \; will run the rm command for every file, so it is not very efficient (slow)
  • Here is the command
find /backups/nsx/ -type f -mtime +90 -exec rm {} +

Run A Cron Job

  • Enter Crontab
    • crontab -e
  • To delete everyday at midnight for files older than 90days in the /backup/nsx/ folder
    • Press the i key to insert
    • Paste in:
    • 0 0 * * * find /backups/nsx/ -type f -mtime +90 -exec rm {} +
    • Hit the esc key
    • then type :wq
    • press enter

About Daniel Fredrick

Technology enthusiast, Programmer, Network Engineer CCIE# 17094

View all posts by Daniel Fredrick →

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.