Work the Shell - More Fun with Days and Dates
I received a very interesting note from a reader—a note that referred to a very interesting problem:
Many UNIX commands (for example, last) and log files show brain-dead date strings, such as “Thu Feb 24”. Does anybody out there have a script that will convert that to a year, given a five-year interval and defaulting to the present?
Given a day of the week, a month and a day, is it possible to calculate quickly the most recent year in the past when that particular date occurred on that day of the week? Of course it is!
Various formulas exist for calculating this sort of thing, but I realized pretty quickly that the handy cal utility can do the work for us. If you haven't experimented with it, you'll be surprised at what it can do. Here are two quick, relevant examples:
$ cal
March 2011
Su Mo Tu We Th Fr Sa
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
$ cal mar 2007
March 2007
Su Mo Tu We Th Fr Sa
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
Any light bulb starting to glow for you? If you know the month and day, you simply can go backward looking at that month's day-of-week layout until finally you find a match.
In a rudimentary fashion, the basic idea can be illustrated with a loop, like this:
repeat
cal $month $year | grep $day
if day-of-week matches
echo date $month $day most recently occurred in $year
else
year=$(( $year - 1 ))
end repeat
Of course, the problem is a bit more complicated (as they always are), partially because of the complexity of calculating what day a specific date occurs in the cal output. There's another complication too, however; the requested date actually might have occurred in the current year, so it's not as simple as starting with the year 2010 and going backward.
The first task is to figure out how to get the information from the user. We'll have only three input parameters and do relatively little testing for misspelled day names and so on:
if [ $# -ne 3 ] ; then echo "Usage: $(basename $0) weekday month day" echo " (example: $(basename $0) wed aug 3 )" exit 1 fi
That's straightforward and pretty typical, offering a nice usage tip if you forget how to use the script. As is typical of scripts, we return a nonzero result upon error too.
We can't work with completely arbitrary data, however, so when we grab the first few parameters, we'll transliterate them into lowercase and chop off all but the first three letters:
weekday=$(echo $1 | tr '[[:upper:]]' '[[:lower:]]'; | cut -c1-3)
month=$(echo $2 | tr '[[:upper:]]' '[[:lower:]]'; | cut -c1-3)
day=$3
Given “Monday, February 8”, it'd be converted automatically to “mon” and “feb” for subsequent testing.
We also need the current date fields for testing, and to do this, I'll demonstrate a very neat trick of date that makes this incredibly efficient:
eval $(date "+thismonth=%m; thisday=%d; thisyear=%Y")
The eval function interprets its argument as if it were a direct script command. More interesting, date can output arbitrary formats (as documented in strftime if you want to read the man page) by using the + prefix, with %m the month number, %d the day of the month and %Y the year. The result is that date creates the string:
thismonth=03; thisday=01; thisyear=2011
which then is interpreted by the shell to create and instantiate the three named variables. Neat, eh?
It turns out that users can specify a month by name or number on the command line. If it's already a number, it'll survive the transforms intact. If it's a name though, we also need the number, so we can figure out whether the date specified could be earlier this year. There are several ways to do this, including a case statement, but that's a lot of work. Instead, I'll lean on sed as I quite frequently do:
monthnum=$(echo $month | sed 's/jan/1/;s/feb/2/;s/mar/3/;s/apr/4/;s/may/5/;s/jun/ ↪6/;s/jul/7/;s/aug/8/;s/sep/9/;s/oct/10/;s/ ↪nov/11/;s/dec/12/')
Here's where a misspelled month name is a problem, but that's a challenge beyond the scope of this script. For now, however, we'll just roll with it.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- What's the tweeting protocol?
- Readers' Choice Awards
- New Products
- RSS Feeds
- Dart: a New Web Programming Experience
- Reply to comment | Linux Journal
9 hours 47 min ago - Reply to comment | Linux Journal
12 hours 20 min ago - Reply to comment | Linux Journal
13 hours 37 min ago - great post
14 hours 12 min ago - Google Docs
14 hours 35 min ago - Reply to comment | Linux Journal
19 hours 23 min ago - Reply to comment | Linux Journal
20 hours 10 min ago - Web Hosting IQ
21 hours 44 min ago - Thanks for taking the time to
23 hours 20 min ago - Linux is good
1 day 1 hour ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
GNU `date' is enough...
As we are talking about Linux, the GNU `date' utility could be far more clever than you might thought, so there is no need to mess with the output of `cal'...
Quick hint:
date -d "Sep 25 2008" +%Adate -d "Sep 25 2008" +%uBut this probably is GNU only, AFAIK, at least the BSD `date' does not have such magic.
Here is an `sh' script listing I just crafted:
#!/bin/sh export LC_TIME=C usage() { cat <<! USAGE: ${0##*/} WEEKDAY MONTH_NAME Day ${0##*/} WEEKDAY MONTH-DAY ${0##*/} WEEKDAY MONTH/DAY ! } if [ $# -ne 3 -a $# -ne 2 ]; then usage exit 1 fi if [ $# -eq 3 ]; then # GNU `date' accepts "Sep 25 2008" fmt="$2 $3 %d" else # And also accepts "2011-9-25" or "9/25/2011" case "$2" in *-*) fmt="%d-$2" ;; */*) fmt="$2/%d" ;; *) echo "Uknown date: $2" usage exit 1 ;; esac fi case $(echo $1 | tr '[:upper:]' '[:lower:]' | cut -c1-3) in mon) weekday=1 ;; tue) weekday=2 ;; wed) weekday=3 ;; thu) weekday=4 ;; fri) weekday=5 ;; sat) weekday=6 ;; sun) weekday=7 ;; *) echo "$1: Unknown weekday" exit 1 ;; esac MY_DATE_FMT="%Y/%m/%d" MY_WDAY_FMT="%A" MAX_TRY=5 y0=$(date +%Y) i=0 found=0 while [ $i -lt $MAX_TRY ]; do y=$((y0 - i)) str=$(printf "$fmt" $y) if ! j=$(date -d "$str" +%u); then # `date' will complain, so I keep quiet exit 1 fi if [ $j -eq $weekday ]; then echo $(date -d "$str" +$MY_DATE_FMT) is \ $(date -d "$str" +$MY_WDAY_FMT) found=1 fi i=$((i + 1)) done test $found -eq 0 && exit 1 exit 0