Work the Shell - Function Return Codes and Daylight Calculations

 in
Determining whether it's night or day (using bash, of course).
Sunrise, Sunset

Don't worry, I won't burst into a song from Fiddler on the Roof, but sunrise and sunset times are very dependent on not only the time of year but also on your location.

After digging around quite a bit, it seems like Almanac.com is one of the easiest sites to work with, so that's what I'll use. A sunrise/sunset query to Almanac.com ends up with a URL of this form: http://www.almanac.com/astronomy/rise/zipcode/80302/2010-08-01.

You'll have to use date to calculate the current date in the proper format and hard-code the local zipcode into the function.

As with most sites, the HTML generated by the Almanac.com result is not parse-friendly, so I had to dig around for a while to figure out how to proceed. Here's what I came up with:


yourzip="80302"      # set this to your local zip code

request="http://www.almanac.com/astronomy/rise/zipcode"

thedate="$(date +%Y-%m-%d)"
url="$request/$yourzip/$thedate"
curl --silent "$url" | grep rise_nextprev | \
  cut -d\< -f28-30

You can see that the zipcode is indeed hard-coded, and notice how I use the $() notation to grab the date in YYYY-MM-DD format. Curl gives you the resultant HTML page, grep finds the one line you're interested in, and then cut chops out the following snippet:


td> 5:38 A.M.</td><td> 8:34 P.M.

There are a few more hoops to jump through, so you can pull out the hour and minute of sunrise and sunset separately (as you'll have to test that way). Here's the code I came up with:

raw="$(/usr/bin/curl --silent "$url" | \
  grep rise_nextprev | cut -d\<-f28-30)"
sunrise="$(echo $raw | cut -d\  -f2)"
sunset="$(echo $raw | cut -d\  -f4)"
srh=$(echo $sunrise | cut -d: -f1)
srm=$(echo $sunrise | cut -d: -f2)
ssh=$(echo $sunset | cut -d: -f1)
ssm=$(echo $sunset | cut -d: -f2)

You could make it a bit faster by avoiding the intermediate calculations of sunrise and sunset, but on modern Linux systems, it should be a matter of milliseconds, so let's leave it just like that.

There's one more important tweak: sunset hour (ssh) needs to be on a 24-hour clock, as that's what you're getting from the date invocation shown earlier. It turns out that you can drop the cut subshell invocation into a calculation:

ssh=$(( $(echo $sunset | cut -d: -f1) + 12 ))

Yes, it works. It looks like I'm moving into LISP territory, but fortunately not!

To work properly, the script needs to do three tests:

  • Whether it's sunrise hour and greater than sunrise minute.

  • Whether it's greater than sunrise hour but less than sunset hour.

  • Whether it's sunset hour but less than sunset minute.

Here's how that looks as script:

if [ $hour -eq $srh -a $min -ge $srm ] ; then
  return 0    # special case of sunrise hour
fi

if [ $hour -gt $srh -a $hour -lt $ssh ] ; then
  return 0    # easy: after sunrise, before sunset
fi

if [ $hour -eq $ssh -a $min -le $ssm ] ; then
  return 0    # special case: sunset hour
fi

Voilà! Kinda neat, if I say so myself.

My full implementation of isdaytime is available on the Linux Journal FTP server at ftp.linuxjournal.com/pub/lj/listings/issue198/10860.tgz.

Dave Taylor has been hacking shell scripts for a really long time, 30 years. 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.

______________________

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.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Dave -- your "Dealing with

pj's picture

Dave -- your "Dealing with Spaces in Filenames" column in the latest Linux Journal (cover date February 2011) ends by stating you would like to open the issue of spaces in filenames for discussion on the Linux Journal discussion boards.

I came here intending to add a suggestion to such a discussion ... but didn't find a thread specific to that topic.

Is there some place you would suggest I go?

Spaces in filenames

jtshoe's picture

Dave, this is not relevant to this particular article, but rather to the general issue of handling spaces in filenames in bash scripts. A few years ago I was taught a drop-in replacement for the for / in loop that properly handles spaces in filenames. Once you reprogram your brain to use this instead of the for loop, you will be free to enter spaces in filenames at your leisure. Say you want to iterate over the output of the find command, in this case, files that end in .txt:

for f in `find . -name "*.txt" -type f`; do echo "file: $f"; done

A file with a single space will create two different lines. Instead, use the while read command:

find . -name "*.txt" -type f | while read f; do echo "file: $f"; done

Enjoy!

A couple nits

Michael Cook's picture

The statement

hour=$(date +%H)

should be

local hour=$(date +%H)

Otherwise, you're modifying the global variable $hour, and
any serious programmer knows it's bad form to have subroutines
or functions set or alter global variables.

And

function daytime
{

should be

daytime ()
{

if you care about being POSIX compliant. The former is a bash-ism and is not recognized by some shells (like dash).

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState