bash 的语法真是反人类啊,反人类啊啊啊
#!/bin/bash # created: 2015-10-10 13:24:15 size=204800 echo "loop delete oldest log file until directory size < "$size" KB" while [ 1 ]; do directory_size=$(du -s | cut -f1) if [ "$size" -gt "$directory_size" ]; then echo "break at directory_size "$directory_size" KB" break else echo "directory_size "$directory_size" KB, continue" fi oldest_log_file=$(ls -tr1 *.log | head -n 1) if [ -z "$oldest_log_file" ]; then echo "no more log files to delete, break" break fi echo "deleting "$oldest_log_file"..." rm -rf $oldest_log_file done;
上面没有考虑相对路径问题,crontab 中一般都是绝对路径执行的,修改如下
#!/bin/bash # created: 2015-10-10 13:24:15 cd /data/log/unified1.0 if [ $? -ne 0 ]; then echo "cd dir failed" exit -1 fi size=204800 echo "loop delete oldest log file until directory size < "$size" KB" while [ 1 ]; do directory_size=$(du -s | cut -f1) if [ "$size" -gt "$directory_size" ]; then echo "break at directory_size "$directory_size" KB" break else echo "directory_size "$directory_size" KB, continue" fi oldest_log_file=$(ls -tr1 *.log | head -n 1) if [ -z "$oldest_log_file" ]; then echo "no more log files to delete, break" break fi echo "deleting "$oldest_log_file"..." rm -rf $oldest_log_file done;
上面的修复还是没有考虑权限,可能出现死循环,修复如下
#!/bin/bash # created: 2015-10-10 13:24:15 cd /data/log/unified1.0 if [ $? -ne 0 ]; then echo "cd dir failed" exit -1 fi size=204800 echo "loop delete oldest log file until directory size < "$size" KB" while [ 1 ]; do directory_size=$(du -s | cut -f1) if [ "$size" -gt "$directory_size" ]; then echo "break at directory_size "$directory_size" KB" break else echo "directory_size "$directory_size" KB, continue" fi oldest_log_file=$(ls -tr1 *.log | head -n 1) if [ -z "$oldest_log_file" ]; then echo "no more log files to delete, break" break fi echo "deleting "$oldest_log_file"..." rm -rf $oldest_log_file if [ $? -ne 0 ]; then echo "delete file failed" break fi sleep 1 done;