zoukankan      html  css  js  c++  java
  • shell脚本删除N天前的目录-----附linux和mac上date命令的不同

    背景:
    每日构建的东西。按日期放到不同的目录里。

    现在天的构建放到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}*会相应不上。

    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/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

  • 相关阅读:
    讲一下创业公司的技术架构演进
    Nginx二级域名配置
    Java分页下载
    Solr6+IKAnalyzer分词环境搭建
    消息发送平台简单架构设计
    优先级线程池实现
    Spring缓存框架原理浅谈
    Archaius 原理
    SpringCloud+Consul 服务注册与服务发现
    EndPoint详解
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/7262827.html
Copyright © 2011-2022 走看看