Script to delete old files

I recently did something like a private file sharing, and to not control what users are uploading, added a script in cron that files that were deleted automatically for more than 3 days.

An example of a command to delete files with more than N days:

find /var/www/share/ -type f -mtime +N -exec rm {} \;

If you need to delete the directories and all that is in them, then this command:

find /var/www/share/ -type d -mtime +N -exec rm -rfv {} \;

You can also write logs (and do not forget to configure logrotate):

find /var/www/share/ -type d -mtime +N -exec rm -rfv {} \; >> /dir/log.txt

Instead of deleting, you can check what data is deleted by the command:

find /var/www/share/ -type d -mtime +N -print

Write a command to a file and put it in the desired directory, for example /home/user/
We add a link to this file in /etc/crontab. The scheduler will execute it every day at 4 am on behalf of the user “www-data” and thus will delete files that are stored longer N days:

0 4 * * * www-data /home/user/ > /dev/null 2>&1

See also my articles:
How to change file date in linux
Script to check the free space on the HDD

Leave a comment

Leave a Reply