如何在Bash脚本中获取上个月的第一个和最后一个日期? [英] How can I get the 1st and last date of the previous month in a Bash script?
问题描述
我已经安排了一个Bash脚本在每月的1号运行,但是我需要在其中创建2个变量,以及上个月的1号和最后一个日期.
I have scheduled a Bash script to run on the 1st of the month but I need to create 2 variables in it with the 1st and last date of the previous month, whatever those may be.
是否可以仅使用Bash来做到这一点?
Is it possible to do this using just Bash?
推荐答案
与某些答案不同,此方法适用于每月的31日和其他任何一天.我用它来输出unix时间戳,但是输出格式很容易调整.
Unlike some answers, this will work for the 31st and any other day of the month. I use it to output unix timestamps but the output format is easily adjusted.
first=$(date --date="$(date +'%Y-%m-01') - 1 month" +%s)
last=$(date --date="$(date +'%Y-%m-01') - 1 second" +%s)
示例(今天的日期是2019年2月14日):
Example (today's date is Feb 14, 2019):
echo $first $last
1546300800 1548979199
1546300800 1548979199
要以其他格式输出,请将最终的+%s
更改为其他格式,例如+%Y-%m-%d
,或者在您的语言环境中省略默认格式.
To output in other formats, change final +%s
to a different format such as +%Y-%m-%d
or omit for default format in your locale.
如果需要,您还可以像这样备份任意数量的月份:
In case you need, you can also back up an arbitrary number of months like this:
# variable must be >= 1
monthsago=23
date --date="$(date +'%Y-%m-01') - ${monthsago} month"
date --date="$(date +'%Y-%m-01') - $(( ${monthsago} - 1 )) month - 1 second"
示例输出(今天的日期是2019年2月15日):
2017年3月1日星期三00:00:00 UTC
2017年3月31日星期五23:59:59 UTC
Example output (today's date is Feb 15, 2019):
Wed Mar 1 00:00:00 UTC 2017
Fri Mar 31 23:59:59 UTC 2017
这篇关于如何在Bash脚本中获取上个月的第一个和最后一个日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!