nixCraft Poll

Topics

Executing script or command on the last day of a month

Posted by Vivek Gite [Last updated: October 12, 2006]

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:

Discussion on This Article:

  1. Milton Says:

    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 Says:

    Milton,

    Thanks for pointing out yest tool.

    Appreciate your post.

  3. Heurist Says:

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

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!

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.