Site icon IT Blog

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 -delete

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

find /var/www/share/ -mindepth 1 -maxdepth 1 -type d -mtime +N -exec rm -rfv -- {} +

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

find /var/www/share/ -mindepth 1 -maxdepth 1 -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/ -mindepth 1 -type d -mtime +N -print

Deleting files older than 1 year and deleting empty directories:

find /var/www/share/ -type f -mtime +365 -delete
find /var/www/share/ -type d -empty -delete

Write a command to a file and put it in the desired directory, for example /home/user/share.sh
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/ixnfo.com/share.sh > /dev/null 2>&1

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

Exit mobile version