Tuesday, April 7, 2009

Find and calculate total size of files older than a month

For some applications it is very common to create temporary files or we can say cache files periodically, which if not removed regularly can consume a lot of disk space unnecessarily. Here is a tip which will save you from wondering how to find and get rid of these.

1. Here's a simple script to find and calculate total size of the files found if you just want to know if these exist under your application or not:

#!/bin/bash

export CACHE_DIR=/path/to/Cache/dir
export file_list=/var/log/cachecron/CacheCron.log.`date +"%Y%m%d_%H%M"` ;
export cache_report=/var/log/cachecron/CacheReport.log.`date +"%Y%m%d_%H%M"` ;
export size=0

#### List cache files #########

find $CACHE_DIR -type f -mtime +30 -exec ls -lAh {} \;| awk '{print $9}' > $file_list ;

##### Calculating the size of cache ##########

echo "CACHE Watch for SEVERNAME `date +"%d-%m-%Y"`" > $cache_report;
echo " " >> $cache_report;
echo "List of files is kept at $file_list" >> $cache_report;
echo "Total no. of files found `cat $file_list|wc -l`" >> $cache_report;
for file in `cat ${file_list}`; do
if [ -f "${file}" ]; then
file_size=`ls -l ${file} | awk '{print $5}'`
size=`expr ${size} + ${file_size}`
fi
done
echo " " >> $cache_report;

### Display Consolidated size in MB###########

echo "Overall Cache: $((${size} / 1048576)) MB" >> $cache_report;

#####Overnight mailer for daily log watch#####

mailx -s "CACHE Watch for SERVERNAME `date +"%d-%m-%Y"`" nixtrap@blogspot.com < $cache_report; #####################################


2. That was just to keep a check on log files and track on daily addition of cache files with respect to nuber and size. If this all seems crap to you and you just want to get rid of these without any intimation here's a one liner for you:

$ find /Cache/dir/path -type f -mtime +30 -exec rm -f {} \;

poof !! there goes the crap ... but before running that just make sure what you are going to erase. This one liner will only list the files found:

$ find /Cache/dir/path -type f -mtime +30 -exec ls -la {} \;

No comments:

Post a Comment