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.
- Email this to a friend
- Printable version
- Rss Feed
- Last Updated: Oct/12/2006
{ 3 comments… read them below or add one }
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.
Milton,
Thanks for pointing out yest tool.
Appreciate your post.
date -d tomorrow +%dwill also output tomorrow’s date without needing to work with the TZ environment.