Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4276
  • Last Modified:

How do I get previous months start and end dates in Unix shell script?

Hi,

From any given date in a month I am wanting to work out the start and end dates of the previous month.

For example, in a unix shell script that I am running anytime in November I want to end up with the following two values :

start_date = "20071001"
end_date = "20071031"

Is this possible?

Cheers

Jo
0
JoHarris
Asked:
JoHarris
1 Solution
 
TintinCommented:
If you have GNU date (you didn't mention what Unix flavour you are using), then the following will work

month=`date --date "last month" +%m`
year=`date --date "last month" +%Y`
lastday=`cal $month $year|grep [0-9]|tail -1|awk '{print $NF}'`
start_date=$year${month}01
finish_date=$year$month$lastday


0
 
JoHarrisAuthor Commented:
sorry - should have mentioned which unix flavour ... thats worked an absolute treat though, many thanks!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now