Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the 1st and last date of the previous month in a Bash script?

Tags:

bash

shell

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?

like image 246
user4428391 Avatar asked Jan 13 '15 10:01

user4428391


People also ask

How do I find the last date of a previous month in Unix?

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"


2 Answers

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

like image 179
radio_tech Avatar answered Oct 20 '22 20:10

radio_tech


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"`
like image 39
LogicIO Avatar answered Oct 20 '22 20:10

LogicIO