因工作中需要删除一些非月末的日志脚本,如果是月末则打包存储。编写了一个脚本:
1 #!/bin/sh 2 3 basedir="base_path" 4 5 datem=$1 6 year=${datem:0:4} 7 month=${datem:4:2} 8 day=${datem:6:2} 9 10 #判断参数是否正确 11 if [ $# -ne 1 ] || [ ${$1} - ne 8 ] 12 then 13 echo "Usage: 请输入正确的时间参数“ 14 exit -1 15 fi 16 17 # 拼接时间格式的字符串、 18 dates=${year}"-"${month}"-"{$day} 19 20 if echo $day|grep -q '^0' 21 then 22 day=`echo $day |sed 's/^0//'` 23 fi 24 25 if cal $month $year > /dev/null 2>/dev/null 26 then 27 daym=`cal $month $year|egrep -v "$yezr|Su"\grep -w "$day"` 28 if [ "$daym" != "" ] 29 then 30 echo ok 31 else 32 echo "Error: please input a wright date." 33 exit -1 34 fi 35 else 36 echo "Error: please input a wright date." 37 exit -1 38 fi 39 40 #转换时间格式 41 date=`date -d "${dates}" +%s` 42 43 44 #计算31天之前的时间(因为需求要求31天的间隔,如果需要月末则可以换成月末) 45 date_new=`expr $date_new -2678400` 46 47 48 #将字符转换为时间格式 49 date=`date -d @$date_new "+%Y%m%d"` 50 51 # 重新赋值年月日 52 year=${date:0:4} 53 month=${date:4:2} 54 day=${date:6:2} 55 56 # 获取月末日期 57 curCal=`cal $month $year` 58 enDayofMonth=`echo $curCal | awk '{print $NF}' 59 60 # 判断文件夹是否存在 61 path="${basedir}/$date" 62 63 if [ -d $path ] && [ "$day" -eq "$endDayofMonth" ] ; 64 then 65 cd ${basedir} 66 echo `tar -czvf $date.tar.ga $date/` 67 echo "月末数据备份 时间: `date +%Y%m%d%H%M%S`" >> log.txt 68 echo `rm -rf $date/` 69 echo "月末数据删除 时间: `date +%Y%m%d%H%M%S`" >> log.txt 70 elif [ -d $path ] && [ "$day" -ne "$endDayofMonth" ]; 71 then 72 echo `rm -rf $date/` 73 echo "非月末数据删除 时间:`date +%Y%m%d%H%M%S`" >> log.txt 74 else 75 echo -1 76 fi