您的位置:首页 > 运维架构 > Shell

shell-删除目录下指定日期前的所有文件

2010-04-07 10:59 821 查看
有一批runlog.YYYYMMDD* 的日志文件(文件名中带有年月日信息),需要一次清理指定的日期前/或设置N天前的所有文件。

编写了一个shell脚本,用于完成此项任务。

 

脚本内容:

 

 

#!/bin/sh -
 
#############################################
#          Created by Ma Fanghua                                             #
#                  2010-04-07                                                            #
#############################################
 
help()
{
   echo "the usage of deleteshell"
   echo "deleteshell.sh YYYYMMDD"
   echo "deleteshell.sh -b days_before"
   exit;
}
 
calc_date()
{
    str=`date '+%Y%m%d'`
    days=$clean_before_days
    yy=`echo $str|cut -c 1-4`
    mm=`echo $str|cut -c 5-6` && mm=`expr $mm - 0`
    dd=`echo $str|cut -c 7-8` && dd=`expr $dd - 0`
    sav_dd=$days
    days=`expr $days - $dd`
    while [ $days -ge 0 ]
    do
        mm=`expr $mm - 1`
        [ $mm -eq 0 ] && mm=12 && yy=`expr $yy - 1`
        aaa=`cal $mm $yy`
        bbb=`echo $aaa|awk '{print $NF}'`
        days=`expr $days - $bbb`
    done
 
    dd=`expr 0 - $days`
    #expr $dd : "^.$" > /dev/null && dd=0$dd
    #expr $mm : "^.$" > /dev/null && mm=0$mm
    [ $dd -le 10 ] && dd=0$dd
    [ $mm -le 10 ] && mm=0$mm
    threshold_date=$yy$mm$dd
}
 
 
if [ $# -lt 1 ] ; then
   help;
fi
 
D_DATE=$1
 
while getopts hb: OPTION
do
   case $OPTION in
     h) help;;
     b) echo $OPTARG
        clean_before_days=$OPTARG
        calc_date
        D_DATE=$threshold_date;;
    /?) echo "invalid args"
        exit;;
   esac
done
 
 
D_DATE_LEN=`echo $D_DATE | awk '{printf("%d",length($1))}'`
if (($D_DATE_LEN != 8))
   then
       echo "please input the date with format YYYYMMDD!"
       exit
fi
 
TMP_DATE=`ls runlog.*`
for file_name in $TMP_DATE
do
   DATE_NUM=`echo $file_name | awk -F. '{printf("%s"),$2}' | cut -c 1-8`
   if (($DATE_NUM < $D_DATE))
      then rm -r $file_name
   fi
done
 
 
使用方法
xxx.sh -h
xxx.sh -b n
xxx.sh YYYYMMDD ( 如 xxx.sh 20100407)
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  date file 脚本 input shell 2010
相关文章推荐