bash 如何获得最后一个月?date +%Y%m -d '1 个月前' 在 3 月 30 日不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43113414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the last month? date +%Y%m -d '1 month ago' doesn't work on March 30
提问by mbergmann
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
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.
有一些目录以日期+%Y%m%d 格式命名。现在是 3 月 29/30/31,脚本删除了这个月的所有文件。今天我了解到这种情况是因为没有二月 29/30/31。
How can i fix this?
我怎样才能解决这个问题?
回答by fancyPants
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"
results in
结果是
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")
回答by Ashish K
If you wish to get the date shifted by number of days you provide :
如果您希望将日期按您提供的天数移动:
Number=222
current_date=$(date +%Y%m%d)
past_date=$(date -d "$current_date - $Number days" +%Y%m%d)
echo "$current_date\t$past_date"
If you wish to get for 1 month :
如果您想获得 1 个月:
date -d "$current_date -1 month"
Similarily for one year :
同样为一年:
date -d "$current_date -1 year"