Executing script or command on the last day of a month

Sometime it is necessary to run a command or script on the last day of a month. There is old good hack (I found this somewhere on Usenet) that will decide whether tomorrow is the first day of the next month.

First find out your time zone (such as EDT, PST, IST, GMT etc) using date command:
$ dateOutput:

Wed Jul 12 11:13:41 MST 2006

MST is my time zone. Now type the following command:
$ TZ=MST-24 date +%dOutput:

13

As you see, output is 13 i.e. next day. Let us assume if today is 31st-july-2006 and you type the following command:$ TZ=MST-24 date +%dOutput:

1

Number one (1) indicates that tomorrow is the first day of the next month. Based upon this login you can easily write a shell script:
#! /bin/bash
TOM=$(TZ=MST-24 date +%d)
if [ $TOM -eq 1 ]; then
# commands or script on the last day of a month
# ...
#...
fi

Please note that TZ is the Linux (UNIX) environment variable containing the current time zone identifier (EDT, IST etc). For more information consults the man pages of ctime, date and info pages (info coreutils date) examples section.

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 3 comments… read them below or add one }

1 Milton 10.12.06 at 5:45 pm

Great hack! Another way to actually get the value of the last day of the month is:
“yest +0 ‘%L’” (See sourceforge.net/projects/yest)

The utility also solves other date/time calculation problems.

Milton W.

2 nixcraft 10.12.06 at 5:55 pm

Milton,

Thanks for pointing out yest tool.

Appreciate your post.

3 Heurist 03.21.08 at 2:40 pm

date -d tomorrow +%d will also output tomorrow’s date without needing to work with the TZ environment.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post: Lighttpd: How do I use more than two IP address (bind) for virtual hosting?

Next post: Lighttpd deny access to certain files