`
jacky
  • 浏览: 26066 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

UNIX: Get the date of N days ago

阅读更多
Here is a real practice: House keep log files which have been out of date for N days.

if [ $# -ne 2 ];then
  echo "Usage: $0 [develop|uat|prod] [ N days ago ]"
  exit -1
fi
ENV=$1
N_DAYS_AGO=$2

function getDays {
	_thisMon=$1
	_thisYear=`date +%Y`	
	_div4=`expr $_thisYear \% 4`
	_div100=`expr $_thisYear \% 100`
	_div400=`expr $_thisYear \% 400`
	
	if [ $_thisMon -eq 2 ];then
		if [ $_div4 -eq 0 -a  $_div100 -ne 0 -a $_div400 -ne 0 ];then
			echo 28
		else
			echo 29
		fi
	elif [ $_thisMon -eq 2 -O $_thisMon -eq 4 -o $_thisMon -eq 6 -o $_thisMon -eq 9 -o $_thisMon -eq 11 ];then
		echo 30
	else
		echo 31
	fi
}

logFolder="/script/logs" 
TMP_FILE=.house_keep_log.tmp

#`date +%m`

THIS_YEAR=`date +%Y`
THIS_MONTH=`date +%m`
THIS_DAY=`date +%d`

DUE_YEAR=$THIS_YEAR
DUE_MONTH=$THIS_MONTH
DUE_DAY=$THIS_DAY

if [ $THIS_DAY -gt $N_DAYS_AGO ];then
	DUE_DAY=`expr $THIS_DAY - $N_DAYS_AGO`
else
    _TMP=`expr $N_DAYS_AGO - $THIS_DAY`
	LAST_MONTH=`expr $THIS_MONTH - 1`
	
	if [ $LAST_MONTH -eq 0 ];then
		LAST_MONTH=12
		DUE_YEAR=`expr $THIS_YEAR -1`
	fi
	
	LAST_MONTH_DAYS=`getDays $LAST_MONTH`
	
	if [ $_TMP -gt  $LAST_MONTH_DAYS ];then
		echo "Can NOT accept $N_DAYS_AGO as 'N days ago' parameter!"
		exit -1
	fi
	DUE_MONTH=$LAST_MONTH
	DUE_DAY=`expr $LAST_MONTH_DAYS - $_TMP`
	
	if [ $DUE_MONTH -lt 10 ];then 
		DUE_MONTH="0"${DUE_MONTH}
	fi
fi
echo "The date of today is :$THIS_YEAR-$THIS_MONTH-$THIS_DAY"
echo "The date of $N_DAYS_AGO days ago is :$DUE_YEAR-$DUE_MONTH-$DUE_DAY"

cd $logFolder
touch -t "${DUE_YEAR}${DUE_MONTH}${DUE_DAY}0000" $TMP_FILE
for log in *.log
do 
	ls -l $log
	if [ $log -ot $TMP_FILE ];then
		#log is before FILE_B
		echo "Delete $log"	
		rm -f $log
	fi  
done

rm -f $TMP_FILE


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics