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

来源:互联网 发布:为知笔记登录 编辑:程序博客网 时间:2024/05/17 09:38

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

#! /bin/bashhistoryDir=~/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    fidone

注意事项:
1,historyDir=~/test/后面一定要带/,否则在后面的遍历文件夹时for file in ${historyDir}*会对应不上。

2,在linux下通过today=$(date +%Y-%m-%d)获得格式为2015-06-01类型的日期,通过

tt1=`date -d $tt +%s`

得到整形的时间戳。当然也可以在获得时间的时候就用$(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/bashhistoryDir=~/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          fidoneecho "--------------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

2 0
原创粉丝点击