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:


DIR=/var/www/ytconv/tmp                         # target directory where we should do some cleanup
FILES="*.flv *.3gp *.mp4 *.avi *.mp3"           # file extensions that will be cleaned
let "EXPIRETIME=540*60"                         # expire time in seconds

shopt -s nullglob                               # suppress "not found" message

cd $DIR                                         # change current working directory to target directory

for f in $FILES
	NOW=`date +%s`                              # get current time
	FCTIME=`stat -c %Y ${f}`                    # get file last modification time
	if [[ $AGE -gt $EXPIRETIME ]] ; then
		rm -f $f                                # this file age is more than the EXPIRETIME above, we can delete it

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 Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>