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

Posted on 2007-10-18
Last Modified: 2008-01-09

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?


Question by:JoHarris
    LVL 48

    Accepted Solution

    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}'`


    Author Comment

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

    Featured Post

    Live: Real-Time Solutions, Start Here

    Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

    Join & Write a Comment

    A metadevice consists of one or more devices (slices). It can be expanded by adding slices. Then, it can be grown to fill a larger space while the file system is in use. However, not all UNIX file systems (UFS) can be expanded this way. The conca…
    Java performance on Solaris - Managing CPUs There are various resource controls in operating system which directly/indirectly influence the performance of application. one of the most important resource controls is "CPU".   In a multithreaded…
    Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
    Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now