清理数据脚本

一个目录下有多个ip名目录,ip目录下有多个年份目录,年份目录下有月目录,月目录下有日目录,

脚本删除离当天31天以上数据

#!/bin/bash
currentDir=/home/mission/test/tmp
ip=""
function isLeapYear()
{
year=$1
if [ $(($year%4)) -eq 0 ]; then
	if [ $(($year%100)) -ne 0 ]; then
		return 0
	fi
elif [ $(($year%400)) -eq 0 ]; then
	return 0
else
	return 1
fi
}
function createMonthDir()
{
	year=$1
	month=$2
	mkdir $month
	cd $month
	for((i=1;i<=31;i++))
	{
		case $month in
		1 | 3 | 5 | 7 | 8 | 10 | 12)
		mkdir $i
		;;
		4 | 6 | 9 | 11)
		if [ $i -ne 31 ]; then
			mkdir $i
		fi
		;;
		2)
		if [ $i -lt 29  ]; then
			mkdir $i
		fi
		;;
		esac		
	}
	isLeapYear $year
	if [ $? -eq 0 ] && [ $month == "2" ]; then
	mkdir 29
	fi	
}
function createYearDir()
{
	year=$1	
	cd $currentDir
	cd $ip
	mkdir $year
	for((j=1;j<=12;j++))
	{
		cd $currentDir
		cd $ip 
		cd $year
		createMonthDir $year $j
	}
}
function init()
{
	cd $currentDir
	#echo $currentDir
	ls |grep -v "test.sh"|xargs rm -rf
	ip="192.168.0.1"
	mkdir $ip
	year=2018
	isLeapYear $year
	createYearDir $year
	cd $currentDir
	cd $ip
	year=2017
        createYearDir $year
	cd $currentDir
	ip="192.168.0.2"
        mkdir $ip
        year=2018
        createYearDir $year
        cd $currentDir
        cd $ip
        year=2017
        createYearDir $year
}
function datediff()
{
d1=$(date -d "$1" +%s)
d2=$(date -d "$2" +%s)
ret=$(( (d1 - d2) / 86400 )) 
#echo $ret
if [ $ret -gt $3 ]; then
return 0
else
return 1
fi

}
function main()
{
cd $currentDir
#清除的天数差
day=31
ipList=`ls`
nowYear=`date "+%Y"`
nowMonth=`date "+%m"`
nowDay=`date "+%d"`
for tmpIp in $ipList
do
	#echo $tmpIp
	cd $currentDir/$tmpIp
	yearList=`ls`
	for tmpYear in $yearList
	do
		if [ $(($nowYear-$tmpYear)) -gt 0 ]; then
			rm -rf $tmpYear
		else
		#同年 
			cd $tmpYear
			monthList=`ls`
			for tmpMonth in $monthList
			do
				cd $currentDir/$tmpIp/$tmpYear
				#相差3月以上
				if [ $(($nowMonth-$tmpMonth)) -gt 2 ]; then 
					rm -rf $tmpMonth	
				else
					cd $tmpMonth
					dayList=`ls`
					tmpDay1=$nowYear-$nowMonth-$nowDay  #20180412
					for tmpDay in $dayList
					do						
						tmpDay2=$tmpYear-$tmpMonth-$tmpDay  #20180412
						datediff $tmpDay1 $tmpDay2 $day						
						if [ $? -eq 0 ]; then
							rm -rf $tmpDay				
						fi				
					done
					num=`ls|wc -l`
					if [ $num -eq 0 ]; then
					rm -rf $currentDir/$tmpIp/$tmpYear/$tmpMonth
					fi										
				fi				
			done
		fi
	done	
done
}
#datediff 20180413 20180313
#init函数是用来产生测试的数据,main函数是清理
#init
echo "start clean"
main
echo "finished"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值