Delete files on Linux using a scheduled Cron job

A simple but useful script for periodically removing files in your Linux server.

Testing the command

Lets test the command for deleting old files. Create the /test_script directory:

mkdir /test_script/

Create a test file:

touch /test_script/test_file

Now we can try to delete all files on /test_script running the command:

find /test_script -type f -mtime +7 -exec rm {} +

If we run ls -la /test_script we will see that the file is still there, this is because the file /test_script/test_file has been created recently and therefore it was ignored for not being at least 7 days old. Now we are going to update the “Modification date” making the file older than 7 day using touch:

touch -d "8 days ago" /test_script/test_file

If we execute the command again:

find /test_script -type f -mtime +7 -exec rm {} +

the file /test_script/test_file will be successfully removed.

Create the Script

Now using the previous command we will create a script called delete_old_files.sh, this file will take care of removing the files that are located at /test/my_folder and are older than 7 days.

#!bin/sh
find /test/my_folder -type f -mtime +7 -exec rm {} +

Add the Cron job

Run the following command to open crontab:

crontab -e

Now we need to create a cron job that will be executed every day at midnight. Add the following line to the very end of the file:

0 0 * * * . /path_to_our_script/delete_old_files.sh

Leave a Reply

Your email address will not be published. Required fields are marked *