AIX Tip of the Week

Using the "date" Command to Determine the Last Day of the Month

Audience: All

Date: October 31, 2003
Updated: November 9, 2003

Determining the last day of a month in a shell script can be complicated because each month has a different number of days, and because of leap year. Here's a trick with the "date" command that simplifies this calculation. I use it to archive rotating monthly logs, and run end of the month reports.


# Pacific Time: TZ=-16 (see below for explanation)
if [ `TZ=-16 date +%d` = "01" ]; then   

    # Run these commands ...


The timezone setting (TZ) setting tricks the date command into thinking it is 24 hours ahead. The syntax is counter intuitive. First, the "-" sign means forward, and a "+" sign means backward. Second, "TZ" is relative to GMT time. To illustrate, here are a few examples that set the timezone ahead one day:

GMT: TZ=-24
EST: TZ=-19
CST: TZ=-18
PST: TZ=-16

This trick can be used to calculate yesterday, tomorrow or two weeks from now.

Bruce Spencer,