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?
You have to actually call date twice to get the last day of last month. Here is how: $ date -d "$(date +%Y/%m/01) - 1 day" "+%Y/%m/%d"
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)
Example (today's date is Feb 14, 2019):
echo $first $last
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:
# 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"
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
You can try following date commands regardless of the day you are executing them to get first and last day of previous month
Firstday=`date -d "-1 month -$(($(date +%d)-1)) days"`
Lastday=`date -d "-$(date +%d) days"`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With