bash script — delete files older than specified time

This time we will create a bash script that will delete certain file that older than certain times. This is useful for cleaning up old temporary files. This script will also delete only files that has specified extensions. I’m using this script in my video converter script to cleanup temporary video/audio files so the server hard disk is not quickly full. I suggest you to put this script as a cron job so it will work automatically.

Full bash script source code:

A bit explanation:
DIR variable is the directory where the script should done cleanup, change it as you wish. FILES variable is the file extensions that will be deleted once it’s met the expiration time. EXPIRETIME is the maximum file age, files that older than this value (in seconds) will be deleted (so, in above code, the script will delete files that older than 540 minutes).

The script will then change the working directory to target directory specified above. Check all files that met the file extensions requirement. Take current time in seconds (time since Epoch). Get file last modification time (also in seconds since Epoch). Then check if the file’s age is older than EXPIRETIME to determine whether it should be deleted or not.

Leave a Reply

%d bloggers like this: