views:

57

answers:

3

Hi all

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 are better ways of doing what I am currently trying to do, your suggestions are more than welcome. The script below is throwing an error "unexpected end of file" .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=archivedate +%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
+1  A: 

Look into logrotate. Here is an example of putting it to use.

Hank Gay
A: 

With what you give us, you lack a "done" to end the for loop and a "fi" to end the main if. Please reformat your code and You will get more precise answers ...

EDIT :

Looking at your reformatted script, it is as said : The "unexpected end of file" comes from the fact you have not closed your "for" loop neither your "if"

As it seems that you mimick the logrotate behaviour, check it as suggested by @Hank...

my2c

neuro
A: 

My du -s -D does not show % sign. So you can just do.

curr_size=$(du -s -D)
set -- $curr_size
curr_size=$1

saves you a few overheads instead of du -s -D | awk '{print $1}' | sed 's/%//g.

If it does show % sign, you can get rid of it like this du -s -D | awk '{print $1+0}'. No need to use sed.

Use $() syntax instead of backticks whenever possible

For targfiles=(ls -1rt) , you can omit the -1. So it can be targfiles=( $(ls -rt) )

Use quotes around your variables whenever possible. eg "$zipname" , "$tfile"

ghostdog74