shell脚本:删除旧文件脚本


#!/bin/bash
# Date: 20140328
# Developer: sndapk
# function: delete files in folders.
# exec: bash $0
PATH=/bin:/sbin:/usr/bin:/usr/sbin
IFS='
'
export PATH IFS
log_t="$(date +%F)"
log="/data/logs/cronlog/delete-file/delete-file.$log_t.log"
#定义删除7天前文件的目录
d_7f="/data/backup/a
/data/backup/aa
/data/backup/aaa
/data/backup/a a"
#定义删除30天前文件的目录。
#d_30="/data/backup/b
#/data/backup/bb"
#创建日志目录
if [ ! -d "$(dirname "$log")" ];then
    mkdir -p $(dirname "$log")
fi
#定义一个函数,删除指定目录下一级目录n天前文件。
del_f(){
        dir="$1"
        days="$2"
        if [ -d "$dir" ];then
        f_list="$(find "$dir" -maxdepth 1 -type f -mtime +"$days")"
        while read d_7f_f
        do
            if [ -z "$f_list" ];then
                            echo "$(date +'%F %T'):WARN:  delete file $days(DIR \"$dir\" no file to delete).">>"$log"
                break
            fi
            rm "$d_7f_f" 2>>"$log"
                    if [ $? -ne 0 ];then
                            echo "$(date +'%F %T'):ERROR: delete file $days(\"$d_7f_f\" error).">>"$log"
            else
                            echo "$(date +'%F %T'):INFO:  delete file $days(\"$d_7f_f\" success).">>"$log"
                    fi
        done< <(echo "$f_list")
        else
                echo "$(date +'%F %T'):ERROR: delete file $days(DIR \"$dir\" not exist)." >>"$log"
        fi  
}
#执行:删除7天前的日志文件
del_f "$(dirname "$log")" 7
#执行:删除7天前文件。
while read d_7f_tmp
do
    del_f "$d_7f_tmp" 7
done< <(echo "$d_7f")
#执行:删除30天前文件。
#while read d_30_tmp
#do
#   echo $d_30_tmp
#   del_f "$d_30_tmp" 30
#done< <(echo "$d_30")


你可能感兴趣的:(shell脚本:删除旧文件脚本)