The date command on Unix displays or sets the system date or time. There are a variety of formatting options available.

$ date +"%m"

displays the month(01 to 12)

$ date +"%B"

gives the full month (e.g. January)

See the link for details.

I needed to get the abbreviated last month for one of my scripts. (e.g Nov). It seems that GNU date allows us to use the command as such :

$ date -d"1 month ago"

Sat Dec 1 12:36:42 MST 2007

So, I could get the abbreviated month by saying

$ date -d"1 month ago" +"%b"

It worked fine yesterday. But today(31 Dec) it says that the last month is Dec. When we say “1 month ago” , it tries to look for 31 Nov, and then corrects the date to 1 Dec. That doesn’t work for what I need.

So here is what I did

month=$(date +"%m")
if((${month}==1));then
month=12
else
let month=${month}-1
fi
last_month=`date -d"2007-"${month}"-1" +"%b"`

I get the numeric value of the current month and subtract one . In the last step I make a dummy date with the month I calculated and then use “%b” to get the abbreviated last month.

Powered by ScribeFire.

Advertisements