Click to See Complete Forum and Search --> : getting size of folder


vrek
02-10-2005, 10:58 PM
Im trying to write a script that will periodically check the size of a folder(well two folders but it shouldn't matter) and clear them is over a certain size. How can I get the size of the folder? I would prefer if I could do this is a simple bash script for simplicity but if its only possible in perl that would be ok.
Can anyone help me? I know the du command but how can I render the output so a script could understand it?

pezplaya
02-10-2005, 11:06 PM
du -sh

not sure about using it in a script though.

vrek
02-10-2005, 11:19 PM
du -sh is what Im using now. But every couple of weeks I(or someone else) have to go to the server manually run it to make sure then fun rm -rf on it to dump everything in the two directories. Its such a repetitive task i don't see why a script wouldn't be perfect. The way it is now we don't even know untill people complain that its not working then we go in a empty it and its all better. Its a mail server in case you wondering and the two directories are basically copies and or log files of every mail transaction that happenes.

DrChuck
02-10-2005, 11:21 PM
You might want to skip the "h" option for du, which puts the output in human readable format (kB, MB ...) - the raw byte count will be more useful for a numerical comparison. Try this to load a variable "size":
size=`du -s |awk '{print $1}'`

drChuck

flukshun
02-11-2005, 02:05 AM
perl -e '@cmd = `du -m $target_dir`; system(rm, "-R", $target_dir) if ((split(/\s+/, $cmd[-1]))[0] > $max_megs)'

replace both instances of $target_dir with the full path of the directory you're monitoring, and $max_megs with the max size. stick it in a cron script.

leonpmu
02-11-2005, 11:14 AM
Why don`t you run logrotate??

davisfactor
02-11-2005, 01:49 PM
First, logrotate would be a better solution so you can archive and compress your logs.

But to answer your question, I came up with this. I'm not an expert coder so I'm sure others can come up with something better.


#!/bin/bash

dirsize=$(du -s /home/davis/test/ | awk '{print $1}');

if [ $dirsize > 15000 ]
then
echo "Directory is larger than 15 megs"
else
echo "Directory is smaller than 15 megs"
fi


I have a 17 meg router image in my test folder so the program will output "Directory is larger than 15 megs".

With your program, you can elimiate the else statement if you don't want your program to do anything.

So what I would do would be to put this script in the bin directory of your home folder, chmod +x it, and add something like this to your crontab:

1 * * * * root /home/davis/bin/check_mail_dir.sh

This will run the program on the first minute of every hour.

Hope this helps!