码迷,mamicode.com
首页 > 系统相关 > 详细

shell脚本删除N天前的文件夹-----附linux和mac上date命令的不同

时间:2015-06-02 13:23:42      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:shell   mac   date   linux   删除文件夹   

背景:
每日构建的东西,按日期放到不同的文件夹里。如今天的构建放到2015-06-01里,明天的就放到2015-06-02里,依次类推。时间久了,需要一个脚本删除N天前的文件夹。(本例中N=7,即删除一周前的构建)。
下面直接上代码,linux版:

#! /bin/bash
historyDir=~/test/
today=$(date +%Y-%m-%d)
echo "---------today is $today-----------"
tt=`date -d last-week +%Y-%m-%d`
echo "next is to delete release before $tt"
tt1=`date -d $tt +%s`  #小于此数值的文件夹删掉
#echo $tt1 
for file in ${historyDir}*
do
    if test -d $file
        then
        name=`basename $file`
        #echo $name
        curr=`date -d $name +%s`
        if [ $curr -le $tt1 ]
            then
                echo " delete $name-------"
                rm -rf ${historyDir}${name}
        fi
    fi
done

注意事项:
1,historyDir=~/test/后面一定要带/,否则在后面的遍历文件夹时for file in historyDir?2linuxtoday=(date +%Y-%m-%d)获得格式为2015-06-01类型的日期,通过tt1=`date -d tt+(date +%s)这样直接得到的就是时间戳,不用再转换了,但是日期是默认的年月日小时分秒的格式转换的时间戳。

PS:MAC下不行。

3,linux里通过date -d last-week +%Y-%m-%d来获得一周前的日期。
PS:MAC下没行。
4,通过 if test -d $file来判断文件夹是否存在,-f是判断文件是否存在。name=basename $file 这句话获得文件夹的名字,之后是将名字(也就是日期)转为时间戳比较。

MAC上的代码

#! /bin/bash
historyDir=~/test/
today=$(date +%Y-%m-%d)
echo "---------today is $today-----------"
today1=`date -j -f %Y-%m-%d $today +%s`
#echo "today1=$today1"

#求一周前的时间
tt=$(date -v -7d +%Y-%m-%d)
echo "next is to delete release before $tt"
tt1=`date -j -f %Y-%m-%d $tt +%s`   #linux上可以这样`date -d $tt +%s`  #小于此数值的文件夹删掉
#echo $tt1 
for file in ${historyDir}*
do 
    if test -d $file
    then
    name=`basename $file`
    echo $name
    curr=`date -j -f %Y-%m-%d $name +%s`
    if [ $curr -le $tt1 ]
        then
            echo " delete $name"
            rm -rf ${historyDir}${name}
    fi      
    fi
done
echo "--------------end---------------"

跟linux上不同之处有二:
1,将字符串的时间转为整数的时间戳时,mac上要这样:
today1=date -j -f %Y-%m-%d $today +%s
2,获得7天之前的日期mac上要这样:
tt=$(date -v -7d +%Y-%m-%d)

相关链接:
1,http://willzh.iteye.com/blog/459808
2,http://apple.stackexchange.com/questions/115830/shell-script-for-yesterdays-date

shell脚本删除N天前的文件夹-----附linux和mac上date命令的不同

标签:shell   mac   date   linux   删除文件夹   

原文地址:http://blog.csdn.net/yanzi1225627/article/details/46327467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!