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 stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
You may also be interested in other helpful articles:
- Run a perl or shell script cron job on the first Monday or the Nth weekday of the month
- Download of the day: Easy date manipulation with yest utility under Linux/UNIX
- Shell Scripting: Creating report/log file names with date in filename
- Executing Linux / UNIX commands from web page
- Getting Yesterdays or Tomorrows day with shell date command
Discussion on This Article:
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!


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.