清除最近三天的日志shell脚本
来源:原创
时间:2018-04-18
作者:脚本小站
分类:SHELL
格式一:20180405
#!/bin/bash export LOG_PATH="/log_data/" export THREE_DAYS_AGO_TIMESTAMP=$(date -d "3 days ago" +%s) for dir in $(ls ${LOG_PATH}) do timestamp=$(date -d "${dir}" +%s) dirpath="${LOG_PATH}/${dir}" if [ $timestamp -lt ${THREE_DAYS_AGO_TIMESTAMP} ]; then if [ -d $dirpath ]; then rm -rf ${dirpath} fi fi done
格式二:scriptjc-2018-04-19-04-00-07.zip
#!/bin/bash # # Delete log files 3 days ago # export CODE_DIR="/root/" export PREFIX="scriptjc-" export REGEX="^${PREFIX}[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}\.zip$" export PREFIX_LENGTH=${#PREFIX} export THREE_DAYS_AGO=$(date -d "3 days ago" +%s) if [ ${CODE_DIR:$(expr ${#CODE_DIR} - 1)} != '/' ]; then CODE_DIR=$CODE_DIR'/' fi for var in $(ls ${CODE_DIR}) do if [[ $var =~ $REGEX ]]; then time_stamp=$(date -d ${var:PREFIX_LENGTH:10} +%s) if [ $time_stamp -lt $THREE_DAYS_AGO ]; then path=$CODE_DIR/$var if [ -f $path ]; then echo 'delete file '$var rm -f $var fi fi fi done
根据创建文件的时间:
find /tmp/* -type f -mtime +3 -exec rm {} \;
压缩文件:
#!/bin/bash # ################################################################ # # 检查 LOG_PATH 目录下是否有未压缩的日志,有则压缩,除了当 # 天的,如果磁盘空间过小无法压缩,干掉一些以前的日志,不包括未 # 压缩的。 # ################################################################# # export LOG_PATH="/home/logs/bond-integration/" export DISK_NAME="/dev/mapper/vg_root-lv_root" export COUNT=0 export MAX_DEL_FILE=3 export PREFIX="bond-integration-" export REGEX="${PREFIX}[0-9]{4}-[0-9]{2}-[0-9]{2}.*?" # # 获取已经使用的磁盘空间 # @param # @return int # function desk_used_size { echo $(df -h $DISK_NAME | sed -n '2p' | gawk '{print $5}' | sed 's/%//') } # # 显示磁盘和日志信息 # @param # @return string # function show_infomation { df -h $DISK_NAME ls -lh $LOG_PATH } # # 删除部分已经压缩的日志,直到磁盘空间大于90%,最多删除3个文件 # @param # @return string # function delete_log { local filename for var in $(ls $LOG_PATH) do ext=${var:$(expr ${#var} - 3):3} if [ $ext == '.gz' ]; then filename=$var break fi done flename_length=${#filename} if [ $flename_length -gt 0 ]; then rm -f $LOG_PATH$filename echo "delete file $filename OK" else exit fi if [ $(desk_used_size) -gt 90 ]; then COUNT=$[ $COUNT + 1 ] echo "The current loop is " $COUNT if [ $COUNT -gt $[ $MAX_DEL_FILE - 1 ] ]; then exit fi delete_log fi } echo "--------------------$(date)---------------------" show_infomation # 如果磁盘空间太小删除一部分压缩文件 if [ $(desk_used_size) -gt 90 ]; then delete_log fi # 压缩日志文件,除了当天的 for var in $(ls $LOG_PATH) do if [[ $var =~ $REGEX ]]; then ext=${var:$(expr ${#var} - 3):3} if [ $ext == 'log' ]; then echo "compressing file $var ... " gzip $LOG_PATH$var echo "gzip $var is OK" fi fi done show_infomation