I run bash scripts from time to time on my servers, I am trying to write a script that monitors log folders and compress log files if folder exceeds defined capacity. I know there better ways of doing what I am currently trying to do, your suggestions are more that welcome. Below is my script.
dir_base=$1
size_ok=5000000
cd $dir_base
curr_size=`du -s -D | awk '{print $1}' | sed 's/%//g' `
zipname=archive`date +%Y%m%d`
if (( $curr_size > $size_ok ))
then
echo "Compressing and archiving files, Logs folder has grown above 5G"
echo "oldest to newest selected."
targfiles=( `ls -1rt` )
echo "rocess files."
for tfile in ${targfiles[@]}
do
let `du -s -D | awk '{print $1}' | sed 's/%//g' | tail -1`
if [ $curr_size -lt $size_ok ];
then
echo "$size_ok has been reached. Stopping processes"
break
else if [ $curr_size -gt $size_ok ];
then
zip -r $zipname $tfile
rm -f $tfile
echo "Added ' $tfile ' to archive'date +%Y%m%d`'.zip and removed"
else [ $curr_size -le $size_ok ];
echo "files in $dir_base are less than 5G, not archiving"
fi
I removed unnecessary semicolons, replaced backticks with
$()
(and fixed a place where one was missing), added two missingfi
and one missingdone
, fixed indentation, made the conditionals consistent, quoted variables, replaced a missing variable, removed an unnecessarylet
, removed an unnecessary re-execution ofdate
, some minor general cleanup, commented out a section (with a missingif
andthen
that I added) that will only be reached if the sizes are equal and moved the<=
condition to the next higherif
, removed unnecessarysed
andtail
.It's completely broken, perhaps not all of it was pasted? Found a unclosed if and an unclosed for loop. Plus syntax error with a ">" (replaced with -lt)
This works: http://pastebin.com/aUC3xwa5
You can also add this to the top of it:
If you are using a Red Hat based distro, you should take a look to logrotate program. You can add your custom script to /etc/logrotate.d/ directory. You can use any of the existing files as example:
/etc/logrotate.d/httpd
You can specify compression, size, frequency, retention and many other options.