Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andrijunaedi/7bc1e6c3d0b52e0f7606bd8bed83ba92 to your computer and use it in GitHub Desktop.
Save andrijunaedi/7bc1e6c3d0b52e0f7606bd8bed83ba92 to your computer and use it in GitHub Desktop.
Automate delete files by date in linux

Find and delete files by date

Delete File PHP Sessions older than 60 days

  • Find list files older than 60 days

    sudo find /var/lib/php/sessions -type f -mtime +60 

    +60 : you can change with another days

  • Show count files older than 60 days

    sudo find /var/lib/php/sessions -type f -mtime +60 | wc -l
  • Delete files older than 60 days

    sudo find /var/lib/php/sessions -type f -mtime +60 -delete 

Delete Files with spesific pattern or extension

  • Find list files older than 60 days

    Filename pattern:

    sudo find --name "ci_session*" /var/lib/php/sessions -type f -mtime +60 

    Spesific file extension:

    sudo find --name "*.log" /opt/backup -type f -mtime +60 
  • Show count files older than 60 days

    sudo find --name "ci_session*" /var/lib/php/sessions -type f -mtime +60 | wc -l
  • Delete files older than 60 days

    sudo find --name "ci_session*" /var/lib/php/sessions -type f -mtime +60 -delete 

Schedule execute command delete with cron

Setup cron

  • Crontab edit

    crontab -e

    for first time, you will asking for choice the text editor, default pick [1] Nano

  • Setup cron for everday at 17:00 UTC (01:00 WIB)

    0 17 * * * sudo find --name "ci_session*" /var/lib/php/sessions -type f -mtime +60 -delete 
  • Save

    If you used Nano as text editor, type Ctrl + X, Y and Enter

    Final step look like this : image image

  • Congratulations, you completed setup atomation delete files by date with cron

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment