Work the Shell

Function Return Codes and Daylight Calculations

Dave Taylor

Issue #198, October 2010

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

Last month, I explored exit codes and how decent error correction in your shell scripts always should include testing the value of $? after each meaningful command. Writing bulletproof shell scripts also involves generous use of the test command too, a typical sequence being something like this:

if [ ! -d $DIRECTORY ] ; then
  echo "Error: Directory $DIRECTORY doesn't exist."
  exit 1
fi

date > $DIRECTORY/$file
if [ $? -ne 0 ] ; then
  echo "Error: failed with error $? trying to create $file"
  exit 1
fi

That reminds me, I talk about the test command, but you don't see me actually using it above. Actually, you do. It turns out, for reasons of coding clarity, there's a file called [ in your filesystem that's a link (a hard link) to the test command:

$ ls -l /bin/{[,test}
-r-xr-xr-x  2 root  wheel  63184 May 18  2009 /bin/[
-r-xr-xr-x  2 root  wheel  63184 May 18  2009 /bin/test

Old-school script authors use if test <condition>, and you'll sometimes see that show up, but it's rare nowadays.

This month, I want to finish this discussion by exploring how the return command within your shell scripts allows you to send information back from functions within the script itself.

Figuring Out Daylight Hours

Let's say you're busy programming some sort of game and find that you want to be able to ascertain whether it's daytime or nighttime when the program runs. Perhaps you have a graphical background that changes, just as Gmail has some themes that change based on your local weather.

“Aha!” I can already hear you saying, “figuring out daytime is trickier than you think, Dave!” You're right, of course, but I'll get to that in phase two. In the first phase of this function, let's create a stub that dumbly assumes that 8:00am–6:00pm is daytime, and the rest of the day is nighttime.

This can be implemented easily enough:

hour=$(date +%H)
if [ $hour -ge 8 -a $hour -le 18 ] ; then
  yes, it's daytime
else
  no, it's nighttime
fi

That's fine, but how do you communicate that with the rest of your script without having the entire script live within some big, ugly, if-then-else statement? More important, what about when you want to make the test far more sophisticated, where it's getting sunrise/sunset times from the Internet for the current date and location?

Let's write a function that returns true if it's daytime and false otherwise. Something like this:

function isdaytime
{
  hour=$(date +%H)
  if [ $hour -ge 8 -a $hour -le 18 ] ; then
    return 1
  else
    return 0
  fi
}

You can reference this in your script within an if statement, as follows:

if isdaytime ; then

One of the glitches with this is that you need to use the counter-intuitive return code of 1 for failure and 0 for success. This is similar to using the exit command: you exit with 0 for success and anything else for failure. Another glitch you may recall from last month is that if you are going to be testing the return code, you easily can get messed up if there are any other commands between the invocation and the test—including a friendly debugging echo statement—because the $? will be the exit code of the most recently invoked function or program.

Assuming you want to save the return code for later use, you could invoke the function like this:

isdaytime ; daytime=$?

At this point you may think, “Wait, why not do it like this?”

function isdaytime
{
  hour=$(date +%H)
  if [ $hour -ge 8 -a $hour -le 18 ] ; then
    daytime=1
  else
    daytime=0
  fi
}

Any serious programmer will know the answer. It's bad form to have subroutines or functions set or alter global variables. Why? Because debugging becomes impossible when variables are set or altered anywhere in the script.

Let's seek to be reasonably elegant with our scripting because: a) it's good form, and b) it leads to more easily understood scripts, which is the point of this column, right? So, get serious, and just change the function to return 0 on success and 1 on failure.

Now that you have a function you can expand later and have a way to return a true/false value to the calling script, how might it be utilized?

Here's one way:

if isdaytime ; then
  echo it is daytime
else
  echo it is nighttime
fi

Pretty trivial, but armed with this basic skeleton, let's have another look at the function itself.

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.