如何获得上个月? date +%Y%m -d“ 1个月前”在3月30日无效 [英] How to get the last month? date +%Y%m -d '1 month ago' doesn't work on March 30

查看:355
本文介绍了如何获得上个月? date +%Y%m -d“ 1个月前”在3月30日无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个脚本来删除旧文件。脚本的一部分如下:

I wrote a script to delete old files. Part of the script is following:

lastmonth=`date +%Y%m -d '1 month ago'`
inputdir0=/var/this/directory/${lastmonth}*

if [ `date +%d` -gt 9 ];
then        
    rm -Rf $inputdir0
fi

有一些以日期+%Y%m%d格式命名的目录。
现在是3月29/30/31,脚本删除了该月的所有文件。
今天我了解到发生这种情况是因为没有2月29/30/31。

There are some directories named after the date +%Y%m%d format. Now it's March 29/30/31 and the script deleted all files of this month. Today I learned this happens because there is no February 29/30/31.

我该如何解决?

推荐答案

减去当前月份的天数,您将获得上个月的最后一天。例如:

Subtract the number of days in the current month, and you will get the last day of the previous month. For example:

date +%Y-%m-%d -d "`date +%d` day ago"

结果

2017-02-28

因为您不在乎白天,只想要该月,您将始终获得正确的月份:

Since you don't care about the day and only want the month, you will always get the correct month:

lastmonth=$(date +%Y%m -d "$(date +%d) day ago")

这篇关于如何获得上个月? date +%Y%m -d“ 1个月前”在3月30日无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆