1. 程式人生 > >清理資料指令碼

清理資料指令碼

一個目錄下有多個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"