天天看點

shell删除前一天的目錄并保留月末那天的目錄

[root@linux26 test]# ls

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-24  2010-12-31  44.sh  5.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-23  2010-12-25  3.sh        4.sh   rm.sh

[root@linux26 test]# mkdir 2010-12-22

2010-11-30  2010-12-01  2010-12-18  2010-12-20  2010-12-23  2010-12-25  3.sh   4.sh  rm.sh

2010-11-31  2010-12-17  2010-12-19  2010-12-22  2010-12-24  2010-12-31  44.sh  5.sh

[root@linux26 test]# date

Sat Jan  1 00:20:03 EST 2011

[root@linux26 test]# cat 44.sh 

#!/bin/bash

month_last_day=`date -d '-1 month' +%Y-%m`"-"`cal|xargs echo|awk '{print $NF}'`

last_day=`date -d '-10 day' +%Y-%m-%d`

if [ "$last_day" != "$month_last_day" ];then

    rm -rf $last_day

fi

[root@linux26 test]# sh -x 44.sh 

++ date -d '-1 month' +%Y-%m

++ cal

++ xargs echo

++ awk '{print $NF}'

+ month_last_day=2010-12-31

++ date -d '-10 day' +%Y-%m-%d

+ last_day=2010-12-22

+ '[' 2010-12-22 '!=' 2010-12-31 ']'

+ rm -rf 2010-12-22

[root@linux26 test]# date -s 2011/01/10

Mon Jan 10 00:00:00 EST 2011

+ last_day=2010-12-31

+ '[' 2010-12-31 '!=' 2010-12-31 ']'

vi /etc/crontab

00 07 * * * root /root/clean.sh

service crond restart

即可。

說明:

目錄下每天都會安裝系統時間命名的目錄備份檔案,要求保留月末的那天的檔案目錄,删除檔案原則是保留10天的目錄。以防萬一的時候可以用備份檔案來恢複。是以保留10天,根據時間來。

 本文轉自 liang3391 51CTO部落格,原文連結:http://blog.51cto.com/liang3391/462942