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.
Is it possible to do this using just Bash?
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.
Is it possible to do this using just Bash?
Example:
Will output the first and last day from (monthsback) months ago:
2016-06-01 - 2016-06-30
2016-05-01 - 2016-05-31
The following will set two variables with the start and end of the previous month:
This can be done in two lines, tweak date format to suit.
Running gives:
If you're doing this on the 1st day of the month then you can use something like
But if you're running on another date then I guess you'll need to start from a known reference date.
Due to the varying length of months, I think the most dependable way to do this is to base the calendar offsets from the first day of the month rather than any other arbitrary date and then subtract the number of days...
In the snippet below, you can set
$TODAY
to whatever date you need and$LAST_MONTH_START
and$LAST_MONTH_END
will end up containing the previous month's start and end dates:TEST
example
result
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.
Example (today's date is Feb 14, 2019):
1546300800 1548979199
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:
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