Unix Tip: Last workday of the month
Send in your Unix questions today! |
See additional Unix tips and tricks
We looked at various ways to write scripts that would only run on the last day of the month in the column "Is this the last day of the month?". Determining whether an arbitrary day is the last day of the month can be done in a number of ways, using the cal and/or the date command. For example, if tomorrow is the first, then today must be the last day of the month. This gets us around the complexity of months with 28, 30 or 31 days.
When a reader recently asked how to write a script that would only run on the last workday of the month, a new twist was added to the old problem. A day is the last workday of a month only if it's a weekday and the following weekday falls in the next calender month. So, I came up with two approaches to solving the new challenge.
The most obvious solution is to use the human-friendly output of the cal command. Here's the output from the "cal" command for this month:
January 2007
S M Tu W Th F S
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
|
We can clearly see that Wednesday, the 31st is the last workday in January 2007. To calculate this in a script, we can use a clunky, but very straightforward command such as this:
cal | grep -v "^$" | tail -1 |
This would give us the last non-empty line in the cal output. We still need to pick out the last workday. If the last week in the month looked like this (as it will this June), we don't want to select the last date on the list as this would be a Saturday:
24 25 26 27 28 29 30 |
Instead, we would want to select the 29th -- the next-to-last date on the line. We can do this by counting the dates in the output and selecting the last date on the line only if there are fewer than seven dates.
Sign up for ITworld's Daily newsletter
Follow ITworld on Twitter @IT_world
jfruh
Apple syncing patent can't come soon enough
pasmith
New Twitter features borrow from 3rd party clients
Esther Schindler
Open Source Changes the Software Acquisition Process
mikelgan
How to set up continuous podcast play on the new iTunes
David Strom
Five important Windows 7 mobility features
sjvn
Guard your Wi-Fi for your own sake
Sandra Henry-Stocker
Grepping on Whole Words
Sidekick: The Good News & the Bad News
Either way you look at it Microsoft Data Center management did not follow standards or best practices in this failure. In which case it makes me wonder more about the outsourcing of corporate data much less personal data.
- mburton325
Join the conversation here
Quick, practical advice for IT pros. Made fresh daily.
Want to cash in on your IT savvy? Send your tip to tips@itworld.com. If we post it, we'll send you a $25 Amazon e-gift card.














For your first snippet, what
For your first snippet, what if the last day of the month falls on Sunday?