【问题标题】:AIX Korn Shell - compare date in yyyyMM formatAIX Korn Shell - 以 yyyyMM 格式比较日期
【发布时间】:2021-09-03 05:12:12
【问题描述】:

我正在 AIX 中搜索比较两个日期。 这是 yyyyMM 格式的第一个日期:

three_months_ago=$(( $(date +%Y%m) - 3))

我从文件系统中获得第二个日期并连接文件夹名称:

for dir in /p22_satos/satos/data/*                                                     
do                                                                                 
 echo ${dir}  
 year=$(basename ${dir})
 if [[ $dir = "/p22_satos/satos/data/static" ]];
then
    print "Static dir should not be deleted"
else
    for   subdir in ${dir}/*
     do
       echo ${subdir}
       month=$(basename ${subdir})
       if [ $month -ge 10 ];
       then
         echo ${year}${month}
         echo $three_months_ago
         if [ ${year}${month} -ge $three_months_ago ];
         then            
           echo "The directory should not be deleted"
         else
            echo "The directory should be deleted"
         fi
       else 

        echo ${year}"0"${month}
        echo $three_months_ago
        if [ ${year}"0"${month} -ge $three_months_ago ];
         then            
           echo "The directory should not be deleted"
         else
            echo "The directory should be deleted"
         fi
       fi

       #rm -f $subdir
     done
fi

$three_months_ago 的值为 202103。 我将 2020 文件夹与子文件夹 12 放在一起,因此循环使 202012 日期成为动态。
为什么 ${year}${month} 和 ${year}"0"${month} 总是大于 $three_months_ago 而 if [ ${year}${month} -ge $three_months_ago ] 失败?

【问题讨论】:

  • 我不太了解你的程序,但我可以提供一个计算三个月前日期的 Perl 脚本:github.com/lzsiga/pldate 用法:pldate sub-months 3
  • 我的程序执行一个 for 循环以检查根目录 /p22_sa​​tos/satos/data/ 中的子文件夹名称,并删除超过三个月的文件夹。我们有一个名为 2020 的文件夹,其中有一个以数字格式(1、2、3 等)表示一年中每个月的子文件夹,然后我们有另一个名为 2021、2019 等的文件夹……它滚动时的周期通过文件夹连接与年份相关的文件夹名称和与月份相关的文件夹名称,例如 202012,我们希望将其与 yyyyMM 格式的三个月前相关的日期进行比较。
  • 你可以这样使用前面提到的脚本:pldate today sub-months 3 printf '%Y%m'

标签: date if-statement compare ksh aix


【解决方案1】:
three_months_ago=$(date --date=@$(( $(date +%s) - (3 * 30 * 24 * 3600) )) +%Y%m)

date +%s: 给出自 01/01/1970 以来的当前日期(以秒为单位)

3 * 30 * 24 * 3600: 90 天内的秒数

date --date=@<seconds>:根据自 01/01/1970 以来的秒数计算日期

+%Y%m:输出格式

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 2022-07-07
    • 2014-05-31
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多