我经常在我的服务器上运行bash脚本,我试图编写一个脚本来监视日志文件夹,并在文件夹超出定义的容量时压缩日志文件。 我知道有更好的方法来做我目前正在做的事情,你的build议更受欢迎。 以下是我的脚本。
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
dir_base=$1 size_ok=5000000 cd $dir_base curr_size=$(du -s -D | awk '{print $1}') 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 "Process files." for tfile in ${targfiles[@]} do curr_size=$(du -s -D | awk '{print $1}') if (( $curr_size <= $size_ok )) then echo "$size_ok has been reached. Stopping processes" break else if (( $curr_size > $size_ok )) then zip -r "$zipname" "$tfile" rm -f "$tfile" echo "Added '$tfile' to archive '$zipname.zip' and removed" # else # if (( $curr_size <= $size_ok )) # then # echo "files in $dir_base are less than 5G, not archiving" # fi fi fi done fi
我删除了不必要的分号,用$()replace了反引号(并且修复了一个丢失的地方),添加了两个缺less的fi ,一个缺lessdone ,固定的缩进,条件一致,引用的variables,replace了一个缺失的variables, let ,删除不必要的重新执行date ,一些小规模的一般清理,注释了一个部分( if then我添加了一个缺失),只有在大小相等的情况下才能达到,并将<=条件移到下一个更高, if删除不必要的sed和tail 。
它完全坏了,也许不是全部被粘贴了? 发现一个未closures的,如果和一个未closures的循环。 用“>”加上语法错误(用-ltreplace)
这工作: http : //pastebin.com/aUC3xwa5
您也可以将其添加到顶部:
dir_base=$1 size_ok=5000000 cd $dir_base # the sed is probably unneccessary curr_size=du -s -D | awk '{print $1}' | sed 's/%//g' date=`date +%Y%m%d` zipname="archived$date"
如果您使用的是基于Red Hat的发行版,则应该查看logrotate程序。 您可以将自定义脚本添加到/etc/logrotate.d/目录。 您可以使用任何现有的文件作为示例:
/etc/logrotate.d/httpd
/var/log/httpd/*log { missingok notifempty sharedscripts delaycompress postrotate /sbin/service httpd reload > /dev/null 2>/dev/null || true endscript }
您可以指定压缩,大小,频率,保留和许多其他选项。