Prash's Blog

Linux Cron Job to Delete tomcat temporary files July 22, 2012

Filed under: Uncategorized — prazjain @ 4:37 pm
Tags: , , , ,

 

Every once in a while my tomcat temporary directory will grow in size by few GBs and I had to manually delete files from server. This also meant that I have to continously monitor my server which can be annoying during holidays. So I wrote a cron job to delete these temporary files :
Create a shell script in your home directory (lets assume it is /root for now):


Files=`ls --sort=t /opt/tomcat-7/temp`
for filename in $Files
do
if rm "/opt/tomcat-7/temp/$filename"
then
 echo "Successfully deleted : /opt/tomcat-7/temp/$filename "
else
 echo "Could not delete file : /opt/tomcat-7/temp/$filename "
fi
done

The script first executes the ls command to get the list of file in the directory, sorted by their creation time.
Next we loop through the file list in the for loop.
For every file we use the if condition to check if it could be deleted or not, and according echo the response.

Now we create an entry in cron tab file so that scripts are executed every hour.

crontab -e

Press i to go the insert mode.
Enter the following content in the editor :

0 * * * * sh /root/rm_tomcat_temp_files.sh > out.log 2> err.log

Press Esc, Shift + : + x to save the changes.

This entry create a job which executes the sh with the given shell file as arguments and stdout and stderr are redirected to files for better logging of what is happening.